Introduction

If you’re a solid user of jQuery or just a tinkerer you may have thought to yourself “I have a great idea for a jQuery plugin”.  Your next steps of course would probably be to look at the jQuery documentation and eventually to have a look at someone else’s jQuery plugin source code.  In doing so you may have said to yourself or aloud “From what depths of perdition hath this code been spawned!”  I’ve seen quite a few jQuery plugin source files and they are, how do I put this delicately…written like crap a lot of the time.  Truth is, there’s an easy and elegant way to build jQuery plugins.

A Simple Example

Let’s start with a simple example.  Let’s say you want to build a plugin that changes the color of all the nodes referenced by a selector.  In other words $(".make-me-red").red(); a very simple approach with the plugin actually called red.  Here’s the code:

Some simple HTML

<div class="make-me-red">One</div>
<div class="make-me-red">Two</div>
<div class="make-me-red">Three</div>

The jQuery plugin code

$.fn.red = function(){
    $(this).css("color", "red");
}

Invoke the plugin

$(function(){
    $(".make-me-red").red();
});

Yes, yes, magical…I know.  That’s all there really is to it, let’s walk through the plugin code.  The $ or jQuery reference has an object called fn, functions bound to this object are accessible from the returned selector array.  The this variable referenced in the function body contains all the elements matching the selector at the time of the call.  The css() method call applies the style attribute with color="red" to all matching selector elements.  Easy peasy, now let’s try something a bit more useful.

Let’s create a jQuery plugin that makes use of options being passed in and performs something semi-useful, not too useful, just semi-useful.  Check it out:

Some simple HTML

<div class="make-me-move">Hi There!</div>

The jQuery Plugin Code

$.fn.jiggle = function(options){

    //setup default options
    var defaultOptions = {
        duration: 500,
        amount: 10
    };

    //apply passed in options to default options
    options = $.extend(defaultOptions, options);

    //divide the time into fourths
    var d = options.duration/4;

    //animate the element
    $(this)
        .css("position", "relative")
        .animate({left: -options.amount}, d)
        .animate({left: -options.amount}, d)
        .animate({left: -options.amount}, d)
        .animate({left: -options.amount}, d)
        .animate({left: 0}, d);
}

Invoke the plugin

$(function(){
    $(".make-me-move").jiggle();
});

Now that was a bit more complex, let’s walk through it.  This plugin is called “jiggle”, wonder why.  The first change here is the options variable being passed in.  This variable allows the plugin to be configurable from the calling code.  In this instance we have exposed the duration (in milliseconds) and the amount (movement).  The first thing we do is set default values to handle the case that the calling code does not pass anything, this is the purpose of the defaultOptions.  Next we make a call to $.extend to override any default values passed into the plugin from the calling code by way of “options”.  We then set options to the merged result of defaultOptions and options (where options overrides defaultOptions), that way we have a single reference to all the values we will use.  Finally, we animate the elements by changing the css position and making subsequent calls to the animate method.  Now let’s invoke the same call again with custom values passed in by way of options.

$(function(){
    $(".make-me-move").jiggle({
        duration: 1000
    });
});

Implementing options the way we have in our plugin code allows us to optionally (pun intended) pass some, all or none of the values into the calling code.  With this example we have set the duration to 1 second (1000 milliseconds).  Simple.

Conclusion

Hopefully this quick start will help propel you into the halls of fame in the jQuery plugin community, and if not, that’s cool too 🙂  Thanks for reading.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *