As I am sure everyone is aware by now, jQuery provides a fantastic interface for developing plugins. Here I’ll share the the typical jQuery plugin structure as well as some best practices.
First, we need to define the plugin, we will call ours “colorize”… pretty simple. You’ll want to use the full “jQuery” function call throughout the plugin, as opposed to the “$” alias in the event this plugin gets used in a situation that alias has changed. In short, $ = bad.
jQuery.fn.colorize = function()
That gives us the ability to do something like:
$("#selector").colorize();
Next, we should come up with some sensible default settings for our plugin while also providing a way for users to provide their own settings.
jQuery.fn.colorize = function(options) {
var defaults = {
textColor: "green"
};
var options = jQuery.extend(defaults, options);
};
Now, we have one option, “textColor”, in our plugin, which defaults to green. We make use of jQuery’s extend() function to smash the two objects (options and defaults) together. So, usage of our plugin looks like this:
$("#selector").colorize({
textColor: "red"
});
By calling our plugin in this manner, we override the default “green” setting with “red”. Next, let’s add some code so our plugin actually does something. All we’re going to do is apply the CSS property “color” to the selected element. Note that inside a plugin “this” assumes the role of the selected element.
$(this).css({
color: options.textColor
});
Now, admittedly this plugin is awful in terms of provided functionality. But, at least it does something now. One last tidbit that’s important to include, though.
return this;
It is important to return this if at all possible so as to maintain the chaining ability of jQuery. For example, our plugin supports chaining so we can do this:
$("#selector").colorize({textColor: "blue"}).show(500);
Done.
So, all put together we’ve got something that should look like this:
jQuery.fn.colorize = function(options) {
var defaults = {
textColor: "green"
};
var options = jQuery.extend(defaults, options);
jQuery(this).css({
color: options.textColor
});
return this;
};
That concludes the basics for jQuery plugin authoring. For more information you can always check out the awesome-packed jQuery documentation.