How to create a rounded corner box plugin with jQuery

Recently, we have redesigned one of our projects. The task was to make the web application to look and act more like Web2.0 app. New design looked great and surely it had lot's of rounded corners.

You can download jQuery Rounded Corners plugin.

First, rounded corners were done using CSS, but it got our code cluttered and it introduced a lot of unnecessary HTML markup. Since we had full control of our target audience's browsers and we were sure that they had JavaScript enabled browser we chose jQuery to do all the dirty work. All we have to do to define a box/table/anything to be in a rounded box is to give it a class "boxed" and the rest is done with jQuery.

Here is the final rounded corners jQuery plugin code:

(function($){
  $.fn.extend({
    box: function() {
      return $(this).each(function(){
        $(this).wrap('<div class="box"><div></div><div class="tl"></div><div class="tr"></div><div class="bl"></div><div class="br"></div></div>');
      });
    }
  })
})(jQuery);

CSS looks like this:

/* -- Rounded Box -- */ 
.box{position:relative;background-color:#eee;margin-bottom:25px;padding:10px;} 
.box .tl,.box .tr,.box .bl,.box .br{position:absolute;width:10px;height:10px;} 
.box .tl{background-image:url(images/box-tl.gif);top:0;left:0;} 
.box .tr{background-image:url(images/box-tr.gif);top:0;right:0;} 
.box .bl{background-image:url(images/box-bl.gif);bottom:0;left:0;} 
.box .br{background-image:url(images/box-br.gif);bottom:0;right:0;} 
.box .bg-white{background-color:#fff;padding:10px;}

How to set default settings in your jQuery plugins

Recently we had a post about automatically adding row count to your tables and then made a plugin out of it. We could further improve our plug-in by providing an option to let plug-in users to overwrite default setting.

For example plugin users could provide a CSS class to set to the added column or change the default "#" in the column header to some other meaningful text.

This is all possible by letting users of your plugin to provide their setting.

For example, in our table row count plugin, users could do this:

$('table').addCount({colName : 'Number'});

So this is how you do this:

$.fn.addCount = function(options) { 
  // set up default options 
  var defaults = { 
    colName:      '#', 
    colWidth:     100, 
    addCssClass:  true, 
    colClass:     'mycolumn', 
  }; 

  // Overwrite default options 
  // with user provided ones 
  // and merge them into "options". 
  var options = $.extend({}, defaults, options); 

  /* 
    If user provided only "colName" 
    option then default options for 
    other 3 variables will be added 
    to "options" variable. 
  */ 

  return this.each(function() { 
    /* Now you can use 
     "options.colWidth", etc. */ 
    console.log(options); 
  }); 
}; 

The key line here is var options = $.extend({}, defaults, options); This line merges options and defaults variables adding missing properties in options variable from defaults variable.

Here is a great example from documentation page of jQuery.extend() that gives a good example about $.extend() method.

var empty = {} 
var defaults = { validate: false, limit: 5, name: "foo" }; 
var options = { validate: true, name: "bar" }; 
var settings = $.extend(empty, defaults, options);

Namespace your JavaScript function and variable with jQuery

We all know that global variable are evil. Namespacing  your variables and methods is now considered a good practice and shows your awareness about the trends. Anyway, I thought how can I namespace my variables and methods in jQuery. Well, first off, I can easily extend jQuery with custom written plugins.

$.fn.extend({
  myNamespaced: function(myArg){
    return 'namespaced.' + myArg;
  }
});
jQuery().myNamespaced('A');
$().myNamespaced('A'); // Shorthand $()
// Outputs: namespaced.A

Now my functions are namespaced and would not conflict with any other already declared functions with the same name. This is great, but to access my functions or variables I have to call jQuery(). The code still looks like chaining not namespacing. To declare your variables or functions in jQuery namespace you can extend the core jQuery object itself using jQuery.extend() rather than jQuery.fn.extend().

$.extend({ 
  myNamespaced: function(myArg){ 
    return 'namespaced.' + myArg; 
  } 
}); 
jQuery.myNamespaced('A'); 
$.myNamespaced('A'); // Shorthand 
// Outputs: namespaced.A

As you can see, now I can call my functions and properties without parenthesis after jQuery object. Now my functions have a jQuery namespace and will not conflict with other functions that might have the same name.

TIP:
Use $.extend({}) to namespace your fields and methods.

Object-Oriented JavaScript, how to achieve public properties/fields

Recently I posted my findings about private fields in JavaScript. So this is a continuation of the post and it talks about public fields in your JavaScript code. So here is a quick example of public properties in your code:

function User() {
  // Private property
  var name = '';

  return {
    // Public property
    classVersion: '1.3',
    prevVersions: ['1.2.3', '1.2', '1'],

    setName: function(newName) {
      name = newName;
    },
    getName: function() {
      return name;
    }
  };
}
var user = new User();
user.classVersion; // 1.3
user.prevVersions; // ['1.2.3', '1.2', '1']

NOTE:
Define an object property name in your return statement and it will be accessible from outside. In other words - public field.

Public and private methods in JavaScript

I have been talking about public and private properties so far. I guess it is time for private and public methods. The idea behind is the same. To make a method public you need to define it in your return object and if you want to make it private you should declare it outside your return.

Basically:

function User() {
  // Private variable
  var name;

  // Private method
  var privateMethod = function(){
    // Access to private fields
    name += " Changed";
  };

  return {
    // Public methods
    setName: function(newName) {
      name = newName;
      privateMethod();
    },
    getName: function() {
      return name;
    }
  };
}
var user = new User();
user.setName("My Name");
user.getName(); // My Name Changed

As you can see, privateMethod and name are declared outside the return object and thus they are made private. Variables declared inside the return object are public and accessible using dot notation.

jQuery 1.2.6 and jQuery 1.3 class selector performance benchmark

Reading about the jQuery 1.3's new selector engine Sizzle and its speed improvements I thought I would do a performance comparison between jQuery 1.2.6 and jQuery 1.3. I was prepared for something good, but the test results blew my mind.

I had a page with one unordered list with 1000 items each with a class (class="1", class="2", etc).

Here is  are the tests and results:
console.time("testClass");
for(i=0;i<100;i++){
    $('.'+i);
}
console.timeEnd("testClass");
/**
* jQuery 1.2.6

1235 ms
1326 ms
1342 ms
=======
1301 ms

*/
/**
* jQuery 1.3

54 ms
52 ms
53 ms
=======
53 ms

*/

As you can see the new selector engine is freakishly fast :) Actually with this specific test it is 25 times fast. Taking into the consideration that class selection is one of the most used selectors, we can assume that our code will work considerably faster.

NOTE:
I have performed the same  tests with selection with id's. The result were exactly the same (9 ms). Taking into the consideration that both versions of jQuery use browser's built in getElementById() function for ID selections, there is not much one can do to beat that.