in jQuery

Simple jQuery Plugin Example

2. Come One, Come All

One of the efficiencies of using jQuery is the ability to apply a bit of code to all elements matching an element without explicitly selecting them all and looping through them. All you do is pass jQuery a selector that indicates which elements on which to act, and jQuery takes care of the iteration.

In order to have jQuery handle the iteration, you have to add your plugin to the jQuery.fn (pronounced “effin” according to jQuery’s site) object rather than just add it as a function on the jQuery object.

The difference is between this:


And this:


There are two ways to add your plugin to the jQuery.fn object: by explicitly defining a property on the object with your plugin name (the preferred way) or by using jQuery.extend() to merge a plugin object onto the jQuery.fn object. Personally I think the first technique is probably more efficient in terms of parsing but I have not tested this assumption. The official jQuery site uses the first technique so that is the one we will use. I mention the second technique simply to let you know that there is another way and you may see it elsewhere. Just be aware that both techniques are correct and both are acceptable.

(function($) {
    $.fn.explainify = function() {
        // Do some kick-ass stuff here