Building a quick and easy jQuery plugin

November 23rd 2013

We've all seen the custom jQuery plugins that people publish, but... do you know how they work?

Let's take a quick tutorial to show you how to emulate one of the more popular ones. This is similar to the example on the jQuery website.

Text Snippet:
$.fn.backgroundColor = function(colour) {
    this.css({background: colour});
};

To use it you'd call:

Text Snippet:
$('.myelement').backgroundColor('red');

Which, if you had an element with a class of 'myelement' then it'd turn 'red'.

You can get pretty in depth with plugins. I try to wrap most my element specific JavaScript into a plugin. It makes it so much easier to get things normalised, and in doing so I prevent a mess of JS down the line.