Skip to main content

Extending jQuery :: Part 1 – Miniature Plugins

By December 30, 2014Blog

We have already extensively covered jQuery plugin development in the 30 minutes guide and it goes through in detail a lot of the nuances of creating a jQuery plugin both large and small. However, sometimes we just need a quick routine without all the getters, setters and prototypes. It is useful to know how to setup a quick mini plugin that will perform some operation on your elements and maintain method chaining for further operations.

There is really only two parts to creating a plugin that maintains method chaining. Take a look below:

$.fn.setColor = function(color) {
    return this.each(function() {
        $(this).css('color', color || '#000');
    });
};

The first main part is to create the plugin name. In the case above we have called it setColor. this means we can now call our method on an element like so:

$('#elem').setColor().show();

We can call our method and continue chaining along as we like. The part that allows us to do is the return this.each() function. That is the next critical piece for this to work. From here it’s just a matter of writing the code for whatever we want our method to do.

In the case above it can set a color so we also provide the option to set the color value with a default to #000 (black) which is the browser default.

Also note inside how we use $(this) and can call any other jQuery methods on the current element inside the each loop. It’s great to be able to quickly create shorthand custom methods like this that our specific to a project’s needs. So it’s important to know these few basic steps to role your own mini jQuery plugins quickly.