The benefit of creating a jQuery plugin normally outweighs that of the nearest alternative. If you use jQuery a lot and you’ve never created a jQuery plugin then you should be asking yourself why!

There’s no doubt that doing it is easy; so easy that I can show you in one line:

jQuery.fn.pluginName = function(){};

So, what’s the point?

Portability

Packaging a common function within a jQuery plugin will normally make it more portable – doing so allows you to easily integrate the plugin into any number of projects within a short amount of time. Reusability, another buzz word, comes hand in hand with this.

Abstraction

I’ve come to realize that creating and using plugins can let you focus on what’s important instead of getting caught up in the details. Even though, strictly, I’m not a fan of hiding behind walls of abstraction I do feel that that it’s a good practice and one that can be utilised extensively in the creation of jQuery plugins.

What I mean by abstraction might be better explained by an example: A project requires validation on several form fields, it must occur on the blur event:

// #1
// Without abstraction / with the details
jQuery('input[name=website]').blur(function(){
    if (this.value.match(/^http:\/\//)) {
        alert('Success!');
    } else {
        alert('Invalid!');
    }
});
 
// #2
// With abstraction
 
// New plugin:
jQuery.fn.validate = function(options) {
    return this.bind(options.event, function(){
        this.value.match(options.pattern) ?
            options.success.call(this) : options.error.call(this);
    });
};
 
// Usage:
jQuery('input[name=website]').validate({
    event: 'onblur',
    pattern: /^http:\/\//,
    success: function() {
        alert('Success!');
    },
    error: function() {
        alert('Invalid!');
    }
});
 
// The above implementation is just an example,
// please don't use alert() to notify users!

The first solution, while shorter than the second, is not very portable and includes all the required functionality within the single handler. The second solution however abstracts away the functionality which remains constant and allows you to individually specify that which is not constant (event type, regex pattern etc.) – it’s a prime example of abstraction.

Time

Yes, it will save you (and your users) time. The time it takes to develop a robust plugin is clearly worth it when you consider what it enables. This is not true in all cases though; only create a plugin when there’s just cause, not for the hell of it!

Containment

Namespacing and scoping are two very prevalent issues in JavaScript. Creating a jQuery plugin means functionality will be logically contained and, as long as you’re proficient, reduce the chance of scope/namespace conflicts (because of that containment).

Community

What better way to contribute to the jQuery community than making and sharing a robust jQuery plugin?

How to…

If I’ve convinced you then I’d suggest the following material: