One of the most powerful features of jQuery is it’s plugin architecture. This allows developers to easily extend jQuery’s functionality.
I’ve decided to extend my table striping example code and turn it into a jQuery plugin. If I have a table with an id of test, I want to be able to call a stripe
function on it’s selector, e.g. $('#test').stripe();
So how do we build this? Well firstly, as it’s a plugin we shouldn’t really be playing with the $ jQuery object incase our user has disabled it. There is a trick to get around this though…
(function($){
// code here can safely use $
})(jQuery);
What’s happening here? Well we’re using a closure to create an anonymous function into which we pass in the jQuery object. The parameter name we use in this function is $ so we can use this inside safely, even if the user has disabled this variable outside our plugin.
Now we have our $ variable we can get on with building the plugin.
$.fn.stripe = function(options) {
// define our function action here.
}
Here we’ve added a function to jQuery called stripe and told it to reference a fuction we’ve defined. Now we need to add the magic to this function to actually do the striping.
return this.each(function() {
$('/tbody:first>tr:even',this).addClass('even');
$('/tbody:first>tr:odd',this).addClass('odd');
});
As a jQuery selector can run over multiple items, we need to make sure we iterate over each of these. We use jQuery’s built in each
function to do this. this refers to the current selector in this case.
Inside, we need to select the first tbody element of the selection, then for each child tr depending if it’s odd or even we set the class of that tr to be either even or odd. This should ensure that nested tables won’t be striped.
That’s great, but what would be even more useful would be the ability to define different class names dynamically so we’re not stuck with the two hardcoded ones.
This is easy to achieve by creating a set of defaults in a private object, passing overrides into our function, and using jQuery’s excellent extend
function to merge the two.
var defaults = {
odd : 'dark',
even : 'lite'
};
var options = $.extend(defaults, options);
Now we can either just call .stripe
directory, or pass in override options like this, .stripe({odd: 'testdark', even: 'testeven')
Putting this all together, we get the following code for our stripe
plugin.
(function($){
$.fn.stripe = function(options) {
var defaults = {
odd : 'dark',
even : 'lite'
};
var options = $.extend(defaults, options);
return this.each(function() {
$('/tbody:first>tr:even',this).addClass(options.even);
$('/tbody:first>tr:odd',this).addClass(options.odd);
});
}
})(jQuery);
A configurable jQuery plugin, in just 13 lines of JavaScript. Marvellous!