jQuery Plugins

This article is an excerpt from jQuery: Novice to Ninja, by Earle Castledine & Craig Sharkie. See more details below.

“Hey, now that everything’s in place—can you just go back and put that menu from phase three into the admin section? And can you add the cool lists you made in the last phase to those lists on the front end—and add the scroller effect you did … you can just copy and paste the code, right?”

Ah, copy/paste: our good friend and worst enemy. Sure, it may seem like a quick way to get a piece of functionality up and running—but we all know that this kind of code reuse can so easily degenerate into our worst JavaScript nightmares. And we can’t let that happen to our beautiful jQuery creations.

You’ve seen throughout the book how extremely useful the jQuery plugin architecture is. We’ve made use of all manner of third-party creations—from styleable scrollbars, to shuffling image galleries, to autocompleting form fields. The good news is that it’s extremely easy to package your code as a plugin for reuse in your other projects—and, if your code is really special, in other developers’ projects as well!

Creating a Plugin

It will only be a short time into your jQuery-writing life before you have the urge to turn some of your code into a plugin. There’s nothing better than seeing a bit of your own code being called from the middle of a jQuery chain! The best part is that it’s a very simple process to convert your existing jQuery into a plugin, and you can make it as customizable as you like.

Setting Up

Before we start, we need an idea for our plugin. Some time ago the client mentioned that he’d like to highlight all the text paragraphs on the page, so that when users moved their mouse over the paragraphs, text would become unhighlighted to indicate it had been read. While you’ll agree it’s far from being the best user interface idea, it’s sufficiently simple to demonstrate how to make a plugin, without having to concentrate on the effect’s code itself.

All we have to do to make a plugin callable like regular jQuery actions is attach a function to the jQuery prototype. In JavaScript, the prototype property of any object or built-in data type can be used to extend it with new methods or properties. For our plugin, we’ll be using the prototype property of the core jQuery object itself to add our new methods to it.

The safest (only!) way to do this is to create a private scope for the jQuery function. This JavaScript trick ensures that your plugin will work nicely, even on pages where a person is using the $ function for non-jQuery purposes:

(function($) {
  // Shell for your plugin code
})(jQuery);

This code can go anywhere in your script, but standard practice is to put it in a separate JavaScript file named jquery.pluginname.js, and include it as you’d include any plugin. Now that you have a stand-alone file, you can easily use it in future projects or share it with the world!

Inside this protective shell we can use the $ alias with impunity. That’s all there is in the way of preliminaries—so it’s time to start to writing a plugin. First we need to give it a name, highlightOnce, and attach it to the jQuery plugin hook, $.fn:

 (function($) {
  // Shell for your plugin code
  $.fn.highlightOnce = function() {
    // Plugin code
  }
})(jQuery);

Internally $.fn is a shortcut to the jQuery.prototype JavaScript property—and it’s the perfect place to put our plugins. This is where jQuery puts its actions, so now that we’ve added our custom action we can call it as if it was built into jQuery.

At this point our code looks like a jQuery plugin, but it won’t act like one—there’s still one more task left to do. If we were to perform some operations inside our plugin code now, we would actually be working on the entire selection at once; for example, if we ran $('p').highlightOnce(), we’d be operating on every paragraph element as a single selection. What we need to do is work on each element, one at a time, and return the element so the jQuery chain can continue. Here’s a fairly standard construct for plugins:

// Plugin code
return this.each(function() {
  // Do something to each item
});

So you now have a nice skeleton for creating simple plugins. Save this outline so you can quickly create new plugins on a whim!

Adding the Plugin’s Functionality

Our highlightOnce plugin is ready to roll, so let’s give it a job to do. All the structure we’ve added so far is just the scaffolding—now it’s time to create a building! The type of code we can run in the guts of our plugin is exactly the same as the code we’re used to writing; we can access the current object with the $(this) construct and execute any jQuery or JavaScript code we need to.

The first function our plugin needs to accomplish is to highlight every selected element, so we’ll just set the background to a bright yellow color. Next, we need to handle when the user mouses over the element so we can remove the highlight. We only want this to happen once, as soon as the element is faded back to the original color (don’t forget, we need the jQuery UI Effects component to do that):

// Do something to each item
$(this)
  .data('original-color', $(this).css('background-color'))
  .css('background-color', '#fff47f')
  .one('mouseenter', function() {
    $(this).animate({
      'background-color': $(this).data('original-color')
    }, 'fast');
  });

There just happens to be a jQuery action that fits our needs exactly: the one action. Functionally, the one action is identical to the bind action we saw earlier, in that it lets us attach an event handler to our element. The distinction with one is that the event will only ever run once, after which the event will automatically unbind itself.

For our code, we save the current background color in the element’s data store, then bind the mouseover event to the DOM elements that are selected. When the user mouses over the element, our code runs and the background color is animated back to the original. And with that, our plugin is ready to be used:

$('p')
  .hide()
  .highlightOnce()
  .slideDown();

It’s quite exciting: our functionality is captured in a chainable, reusable plugin that we’ve nestled in between the hide and slideDown actions. Seeing how 11 lines of code was all that was required (and six of those are stock-standard plugin scaffolding!), you can see it’s worth turning any functionality you intend on reusing into a plugin!

Adding Options

jQuery plugins are an excellent way to produce reusable code, but to be truly useful, our plugins need to be applicable outside the context for which we created them: they need to be customizable. We can add user-specified options to our plugins, which can then be used to modify the plugin’s behavior when it’s put to use.

We’re familiar with how options work from a plugin user’s perspective, as we’ve passed in options to just about every plugin we’ve used throughout the book. Options let us modify the plugin’s functionality in both subtle and more obvious ways, so that it can be used in as wide a range of situations as we can imagine.

There are two types of plugin options: simple values and object literals. Let’s start with the simpler one to see how this works. For our highlightOnce plugin, it seems quite limiting to have the color hard-coded. We’d like to give developers the choice to highlight their elements in any color they’d like. Let’s make that an option:

$.fn.highlightOnce = function(color) {
  ⋮
  $(this).css('background-color', color  || '#fff47f')
  ⋮
};

The plugin can be called with a color, but can also be called without parameters—in which case a default value will be used (thanks to the JavaScript || operator). Let’s highlight our paragraphs in green:

$('p')
  .hide()
  .highlightOnce('green')
  .slideDown();

If you have one or two simple options that are always required, this approach is fine. But when your plugins start to become more complicated, you’ll end up with numerous settings, and your users will want to override some and keep the default values for others. This is where we turn to the more complex object literal notation.

It’s not scary—you already know how to define this type of settings object. We’ve used them for animate, css, and most jQuery UI components. The key/value object has the benefit of only one parameter needing to be defined, in which users will be able to specify multiple settings. Our first step is to set up default values for each option:

$.fn.highlightOnce.defaults = {
  color : '#fff47f',
  duration : 'fast'
}; 

We now have the defaults as an object, so we need to make use of the jQuery $.extend function. This handy function has several uses, but for our purposes, we’ll use it to extend an object by adding all of the properties from another object. This way, we can extend the options the user passes in with our default settings: the plugin will have values specified for every option already, and if the user specifies one of them, the default will be overridden. Perfect! Let’s look at the code:

$.fn.highlightOnce = function(options) {
  options = $.extend($.fn.highlightOnce.defaults, options);

  return this.each( … );
};

Our options variable contains the correct settings inside it—whether they’ve been defined by the user, or by the default object. Now we can use the settings in our code:

$(this)
  .data('original-color', $(this).css('background-color'))
  .css('background-color', options.color)
  .one('mouseenter', function() {
    $(this).animate({
      'background-color': $(this).data('original-color')
    }, options.duration);
  });

As the plugin user, we can specify the color or duration of the highlight—or accept the defaults. In the following example we’ll accept the default color, but override the duration to be 2,000 milliseconds rather than “fast”:

$('p')
  .hide()
  .highlightOnce({duration: 2000})
  .slideDown();

Adding Callbacks

You have seen how callback functions and events can be very useful. Many of the effects and controls throughout the book have relied on them—and many of the plugins we’ve used have given us access to callbacks to customize their functionality. Callbacks are a mechanism for giving your plugin’s users a place to run their own code, based on events occurring inside your plugin. Generally you’ll have a fairly good idea of what events you’d like to expose to your users. For our highlightOnce plugin, for example, we might want to run additional code when the effect is set up, when the effect concludes, and perhaps when the fade-out commences.

To demonstrate, let’s try exposing a setup event (which will run after the mouseover handlers are attached), and a complete event (which will run after the final animate action concludes):

$.fn.highlightOnce.defaults = {
  color : '#fff47f',
  duration : 'fast',
  setup : null,
  complete: null
};

The callback functions shouldn’t do anything by default, so we’ll set them to null. When the time comes to run the callbacks, there are a few possible ways of proceeding. If our callback needs to run in the place of a jQuery callback, we can simply provide the function passed in by our users to the jQuery action. Otherwise, we’ll need to call the function manually at the appropriate location:

$(this)
  .data('original-color', $(this).css('background-color'))
  .css('background-color', options.color)
  .one('mouseenter', function() {
    $(this).animate(
      {'background-color': $(this).data('original-color')},
      options.duration,
      options.complete
    );
  });

  // Fire the setUp callback
  $.isFunction(options.setup) && options.setup.call(this);

Above we can see both types of callbacks. The complete callback handler is easy: the effect is completed when the animate action is finished, and the animate action accepts a callback function itself, so we just pass the function along. No such luck with the setup handler, though—we’ll have to fire that one ourselves. We turn to jQuery and a dash of advanced JavaScript to execute the code. First, we check to see if the callback is a function with the handy $.isFunction jQuery action that returns a Boolean value: true if the callback is a function, false if it’s not. If it’s the latter (which is most likely because the user left the defaults as they were, in which case it will still be null), there’s no point trying to execute it!

More Utility Functions

In addition to $.isFunction, jQuery also provides the following functions: $.isArray (for testing if a variable is an array), $.isPlainObject (for simple JavaScript objects), and $.isEmptyObject (for an object that has no properties). These functions provide you with a number of ways to ascertain the nature and properties of a JavaScript construct.

If the callback has been defined, we need to run it. There are several ways to run a JavaScript function, and the easiest is to just call it: options.setup(). This will run fine, but the problem is that it’s called in the scope of the default object, instead of in the scope of the event’s target element (as we’re used to). So the callback function would be unable to determine which DOM element it was dealing with. To remedy this, we use the JavaScript method call. The first parameter you pass to call will override this in the method you’re calling. In our example, we pass in this, which is the DOM element we want.

With the scope corrected, we can now use $(this) inside the complete event handler to slide up the element once the effect is done and dusted:

$('p')
  .hide()
  .highlightOnce({
    color: '#FFA86F',
    complete: function() {
      $(this).slideUp();
    }
  })
  .slideDown();

jQuery-style Callback

You might have noticed that the jQuery callbacks seem better integrated than our plugin’s named events. For example, in the hide action, you can specify the callback function as either the first (and only) parameter, or you can include the speed parameter and then the callback function. It’s unnecessary to include a key/value pair as we did above. What’s the secret? It turns out to be a little bit of a JavaScript hack. If you detect that the first parameter is a function, rather than an object, you can assume that only a callback has been specified, so you shift the parameters over.

Here’s a (truncated) example from the jQuery core library, part of the Ajax load action. The params parameter is optional, so if it isn’t supplied the second parameter is assumed to be the callback:

load: function( url, params, callback ){
  // If the second parameter is a function
  if ( jQuery.isFunction( params ) ){
    // We assume that it's the callback
    callback = params;
    params = null;

The params parameter is supposed to be an object filled with various settings. But if we detect that it’s actually a function, we assign the function to the callback variable and clear the params variable. It’s a cool trick and a good way to make your plugins feel more jQuery-ish.

Let’s modify our highlightOnce plugin to use this callback detection trick:

$.fn.highlightOnce = function(options, callback) {
  if ($.isFunction(options)) {
    callback = options;
    options = null;
  }
  options = $.extend($.fn.highlightOnce.defaults,options);

  return this.each(function() {
    // Do something to each item
    $(this)
      .data('original-color', $(this).css('background-color'))
      .css('background-color', options.color)
      .one('mouseenter', function() {
        $(this).css('background-color', '');
        $.isFunction(callback) && callback();
      });
  });
};
note:Want more?

Check out the book and buy it online at jQuery: Novice to Ninja, by Earle Castledine & Craig Sharkie. You can also download the book’s code archive, check on updates and errata or consult with the thriving community of JavaScript and jQuery developers on the SitePoint Forums.

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

  • techuth

    This is the best post of jQuery plugin and I am sure now I can manage jQuery plugins. Thanks jQuery is the only thing my blog is missing. Thanks