jQuery Plugin Design Patterns: Part I
jQuery plugins come in all shapes and sizes. They perform very simple or very complex tasks depending on their intended use. When it comes time for you to design your own plugin, its really important to understand what patterns other developers use and what will best suits your needs.
As a side note, I have built a number of plugins for my own projects and client work that will never be released. The jQuery community needs to stop thinking of plugins only as releasable, open-source projects, and start thinking of them instead as a reusable pieces of code that can help optimize and DRY up a complex website. Take this little plugin as an example:
$.fn.notice = function(){
return this.slideDown(500).delay(4000).slideUp(500);
}
It simply abstracts the animation for displaying a notice (using jQuery 1.4). Would I ever release this on an open source site? Of course not! But it is still a fully functioning jQuery plugin that can be used over and over throughout a website.
Design Pattern Series Overview
- Basics & Structure (this article)
- Options & Updating
- Callbacks & Custom Events
- Misc. General Practices
Basics
Filename
Every jQuery plugin sits in its own JS file, and is normally named using the following pattern:
jquery.pluginname.js jquery.pluginname.min.js
Released plugins often also have a version number:
jquery.pluginname-1.3.js jquery.pluginname-1.3.min.js
If you end up building a lot of plugins for your website, consider also including a namespace to keep all your files together (And of course you would combine and minify them for production, right?):
jquery.mysite.pluginname.js jquery.mysite.pluginname.js
Basic File Layout
After any comments you choose to put at the top of your file, the very next thing you should have is a self executing anonymous function that will actually wrap your entire plugin. Say what!? Don’t worry, you have seen it before, and it looks like this:
(function($){
... code here ...
})(jQuery);
This gives your plugin a private scope to work in, and also allows your plugin to be used with $.noConflict mode without creating a problem. By passing jQuery into the function, the $ will equal jQuery inside the function even if $ means something different outside your plugin.
Structure
There are three basic structures you will see when you look at released plugins:
Contained Function
In this structure, (almost) all the code to run your plugin is contained within the function used to call your plugin. This is the most common format:
(function($){
$.fn.myPlugin = function(){
return this.each(function(){
// do something
});
}
})(jQuery);
You should use this this structure when you are writing a simple plugin that acts once upon the jQuery result set on each execution. For complex plugins that need to maintain an adjustable state, you should consider the “Class and Function” structure.
Class and Function
In this structure, a class is used and an instance is created for each DOM element in the result set. You may see these objects attached in some way to the DOM elements they modify:
(function($){
var MyClass = function(el){
var $el = $(el);
// Attach the instance of this object
// to the jQuery wrapped DOM node
$el.data('MyClass', this);
}
$.fn.myPlugin = function(){
return this.each(function(){
(new MyClass(this));
});
}
})(jQuery);
You should use this structure if you need to be able to access the object later that is associated with a DOM element. It is far easier to attach a single object vs several key/value pairs using the data() method. In this approach, you can access the object by calling $('selector').data('MyClass'). This functions more like a widget and is a plugin that maintains state and can adjust its state on the fly (Learn how in the next article.).
Note: Widget Factory: The next release of jQuery UI is going to see the addition of a Widget Factory that will be designed to specially assist in developing widget-like plugins.
Extend
In my opinion, this is the least idiomatic way to create a jQuery plugin. It uses the jQuery.fn.extend method instead of jQuery.fn.pluginName:
(function($){
$.fn.extend({
myPlugin: function(){
return this.each(function(){
// do something
},
myOtherPlugin: function(){
return this.each(function(){
// do something
}
});
})(jQuery);
You will find this structure helpful if you need to add a large number of plugin methods to jQuery. I would contend, however, that if your plugin needs to add that many methods, there may be a better way to structure its implementation.
I feel the extend method is used more by programmers transitioning from other JS libraries. I personally find the simple $.fn.pluginName = structure to be easier to read, and more in line with what you will normally see in jQuery plugins.
Up Next
In the next part of this series, we will look at passing options and providing methods for updating settings and functionality after a plugin has been called.
Doug Neiner is an Editor at Fuel Your Coding and an official member of the jQuery Team. He is addicted to new technology, and specifically loves spending time with WordPress, Ruby on Rails and jQuery. Learn more via twitter or his Google Profile.


Great stuff Doug! As I start to learn more about jQuery, I will be coming here as a resource! Cheers!
Nice post Doug!
One thing, shouldn’t it be “jQuery.fn.extend”, not “jQuery.extend” (which extends the jQuery namespace)?
The “class and function” approach is interesting. I’m not too sure I would like having to access a module’s API via data():
$(’#foo’).data(’MyClass’).doSomething(); // doSomething, a method in MyClass’ prototype
It just seems wrong. Is this just a solution to a problem that doesn’t exist? If an instance of MyClass needs to be retained (for whatever reason), then I think it would be better to instantiate the class outside of the plugin mechanism and assign the produced instance to a var, like you normally would:
var instance = MyClass( $(’#foo’) );
There was recently an interesting post on StackOverflow that discussed the “limitations” of jQuery’s plugin API, specifically for more complex solutions that require access to an instance: http://stackoverflow.com/questions/2000597/jquery-vs-yahoo-ui-api-design/2000707
James, I always appreciate when you stop over and discus our posts here!
First, you are totally right, it is $.fn.extend. I have updated the post to reflect that.
As far as the “class and function” approach, we haven’t gotten to the true interaction with it yet. However, it is the design pattern employed by jQuery UI for their widgets. If you instantiate a `dialog` for instance, then call `$(”#dialog”).data(’dialog’)` you can retrieve the instance of the Widget class for the dialog.
A good use case I had for it was a rating system. There were 20 rating widgets, who all maintained their own state independently of the others. However, I also had a ScoreKeeper of sorts that listened for “rating_changed” events on the Rating widgets, and then would access each of the widgets using (through a wrapper) the `data(’RatingWidget’)` and tally up the total.
This method allows you to build fully independent objects that can interact with each other as needed. By exposing the Class behind the object via `data` you allow your widget to be extended or manipulated by other widgets on the page. Of course you can use standard closures to limit what is available on the object. When `.remove()` is called all the `data` is removed from the element.
Back to jQuery UI, as a final example, when you call `.dialog(’open’)` it is actually finding the instance via `data` then applying the function to that instance behind the scenes. You can check it out starting at line 284 in ui.core.js (1.7.2).
Hi, really nice discussion! I’m actually stuck in creating something like the rating widget you described wherein it maintain it’s own data …is there any chance you can explain further especially how jquery ui is designed to allow something like updating it’s option..
$(’.selector’).button(’option’, ‘text’, false);
I have favorited that SO article now. I will throw my two cents in when I get a moment :) Thanks for pointing it out!
Ah, sorry, that should be:
var instance = new MyClass( $(’#foo’) );
What a coincidence, I had just been reading this; http://2007-2010.lovemikeg.com/2009/06/26/the-factory-pattern-in-javascript/
When using Widget Factory, Could I use Mootools(or Prototype) to creat the Class ,then using jQuery “data()” its object ,manipulating DOM ? I like the OO concept ,also like the jQuery dom magic.
Part || Please
Looking forward to Part 2!!!
Part 2 coming?
Great article! Neatly solves the problem of maintaining state.
Will there be a Part 2 Doug?
I’ve been wandering for a few days searching for concise usable info like in this articke. It is really missing rest of the series as it feels like it would be of a great help to jq-plugin-dev-newborn.
Nice article. Thanks =)
However, I disagree about the use of the extend method. That method make the stuff, but it make very (too?) easy to add more than one method to the $.fn object. And adding more than one namespace per plugin should be avoided. This is referenced in the best practices in the Plugin Authoring (http://docs.jquery.com/Plugins/Authoring) as:
“Don’t clutter the jQuery.fn object with more than one namespace per plugin.”
Using the “$.fn.myPlugin = function(){};” forces the developer to use one and only one name per plugin. Also, the Plugin Authoring describe a method to use multiples methods per plugin without pollute the $.fn namespace.
And it is much faster to add a plugin with $.fn. than $.extend() – so, that’s another reason to use the more strict way ;)
Would there be a Christmas special Part 2 by any chance? Considering keeping a promise for Part 3 and 4 as mentioned in the article? It is so difficult to come across well written articles for the remaining parts that those are bound to be an immediate hit.
Wtb part 2. Anyone got experience with plugins for plugins? Ie. I got a text editor plugin and i want pluggable toolbars.
I presume this is the only article seen as this was written a few years ago. For the interest of other readers this is a more up to date article on design patterns: http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/
nice tutorial.. Thanks for your stuff