Developing a jQuery Plugin

Sometimes we get it in our heads that a task is too complex that we just ignore doing it. That's been my mindset when thinking about developing a plugin for jQuery. I've always thought that some of the code I developed would make more sense as a plugin but I just didn't have time to figure it out.

After finally pushing myself into learning about jQuery plugins, I was left saying, "That's it?!" It turns out it's ridiculously easy and I have no idea why I haven't been doing this from day one.

Why a plugin?

First of all, you might ask yourself why you'd want to develop a plugin. The first and best reason is the ability to maintain chainability. When people ask me the best feature of jQuery, I'd probably mention the chainability. It allows you do do things like:

$('.className').addClass('enabled').append('<a href="#">Click here</a>').click( func );

This would take every element with a class name of 'className', add a new class name to it, append some HTML, and set a click event handler. When you develop a plugin, you have the ability to intject your own functionality while still maintaining the chain.

Another reason to develop a jQuery plugin is simply to be consistent with the jQuery ethos. The jQuery ethos, in my opinion, is that the HTML element is king (or queen — lest I be mysoginistic about my HTML elements). It's all about getting elements and then performing actions on those elements.

Now, let's take a look at how to create a plugin, of which there are two possible approaches.

Approach 1: The Function

The documentation has a good example of the functional approach.

jQuery.log = function(message) {
  if(window.console) {
     console.debug(message);
  } else {
     alert(message);
  }
};

In this example, a log function has been attached to the jQuery object. You can then call this in your code using jQuery.log('my message') or $.log('my message'). There's no chainability or HTML elements involved (unless you add that into your code).

Approach 2: The Method

The method approach, gives you access to the current set of HTML elements and allows you to continue the chain. (Cue up the Pretenders, if you must.) Once again, the code is really simple... add the new function to jQuery.fn and make sure to return this.

jQuery.fn.newMethod = function(){
    return this;
};

The this keyword refers to the current jQuery object. You'll have access to jQuery's methods and functions. If you need to perform an action on each element then you can do something like this:

jQuery.fn.newMethod = function(){
    return this.each(function(){
        alert(this);
    });
};

The this keyword within the inner function refers to the current HTML element, which won't have access to the jQuery methods (although, it's as easy as wrapping it in the jQuery object to get those methods back).

Don't use $

When developing a plugin, you'll want to avoid using the familiar dollar function, $, to avoid any conflicts. jQuery has a no-conflict mode for turning the alias on and off. If you want, you can alias the jQuery function within your plugin. It'll be self-contained and avoid any outside conflicts.

Jump in

Check out the jQuery documentation on plugins for more information. Sometimes the most difficult part is just taking the first step!

Published January 24, 2008

Conversation

12 Comments · RSS feed
Remy Sharp said on January 24, 2008

If you do want to use $ in your plugin, the best was is as such:

(function ($) {
  $.fn.newMethod = function () {
    return this.each(function () {
      alert(this);
    });
  };
})(jQuery);
Jonathan Snook said on January 24, 2008

@Remy Sharp: thanks for demonstrating the aliasing. I should have included that snippet in the main article.

Marc Grabanski said on January 24, 2008

@Remy Sharp: You beat me to it. I always use $, but I wrap it with the method you described.

John, thanks for the quick low-down. I started posted a comment and then it turned into a full article. I just wanted to explain the two types of plugins:
jQuery Plugin Actions vs Utilities

Brian Layman said on January 24, 2008

Excellent Jonathan! Thanks for this post!

Damjan Mozetič said on January 24, 2008

I never thought this could be so simple and I'd probably never take the time to look into it myself :) Thanks for the tip!

Liu Leren said on January 25, 2008

I am getting better and better with jquery (and that is not just because of me :) thanx!

Thame said on January 26, 2008

For times when you need something in between a basic method and a full-fledged plugin, it can be handy to extend jQuery directly.

For example:


jQuery.fn.extend({
	sample : function() {
		// do something and keep chaining
		return this;
	},
});
Christopher Hill said on January 27, 2008

Nice article. Generally speaking, there always seems to be a plugin of what I want to do, so I haven't had the need to jump into developing a plugin.

Ariel Flesler said on January 29, 2008

Good article, Mike Alsup made an excellent article on jquery plugins some time ago. http://www.learningjquery.com/2007/10/a-plugin-development-pattern

About "Approach 1"... I usually use the static name for a function that internally calls the method with some specific values. Sometimes the other way around too. That's the case of ScrollTo, LocalScroll and Preload.

Blake said on October 01, 2008

Very good and clear article. Thank you!

Luis said on December 30, 2008

great article, thx! I'm going to give it a try!

sepide said on February 05, 2011

hi
thank you for your article,
please help me,i have added class to website and have written some public static method in class.
now i want to call them with jquery,without webservice,
is there any solution for this work?

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.