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);