How to Write a jQuery Plugin
June 9th, 2010I know there’s a slew and a half of tutorials on this out there, but I’m adding my own to the mix. I’ve been working on a generic template for plugin development and have cobbled together what I feel is a solid one.
First thing first, however, building a plugin is about being a good citizen
- You’ve got a naming convention to deal with. jquery[your plugin name].js
- Be considerate of the $.XXX namespace. Only claim 1, and try to make it both developer friendly and unique. In our case it will be $.plugin
- Always return this.
- Always end with a “;”
- Wrap the entire thing in an anonymous function call, this will protect the plugin from instances where jquery has been renamed.
So, with all that said and done, the skeleton of a plugin looks like this:
1: (function($) {
2:
3: $.fn.myPlugin = function(settings) {
4: var config = {'foo': 'bar'};
5: if (settings) $.extend(config, settings);
6: this.each(function() {
7: // element-specific code here
8: });
9: return this;
10: };
11:
12: var newMethods = {
13: a : function() {
14: var config = {'foo': 'bar'};
15: if (settings) $.extend(config, settings);
16:
17: this.each(function() {
18: // element-specific code here
19: });
20:
21: return this;
22: },
23: b : function() { return this },
24: c : function() { return this }
25: };
26:
27: jQuery.each(newMethods, function(i) {
28: jQuery.fn.myPlugin[i] = this;
29: });
30:
31:
32: })(jQuery);
Note, what this code is doing.
First, we define the core behavior of the plugin, then extend the plugin once. This way we keep our declarations concise, clear and well encapsulated.
We have an established closure structure for shared private functions.
We keep everything encapsulated to protect the jquery namespace as much as possible, and iterate over the child functions to extend the plugin.
PS– most of this is adapted from the jquery extension guide here: http://docs.jquery.com/Plugins/Authoring




