One of the best things about jQuery is its extensibility. If you find yourself writing the same logic over and over across multiple projects, you can package that logic into a **jQuery Plugin**. A plugin is simply a new method that you add to the jQuery prototype.
To create a plugin, you must understand jQuery.fn. This is the alias for the
jQuery prototype. Any function you attach to jQuery.fn becomes available to
every element you select with `$( )`.
A professional jQuery plugin must follow three main rules:
Let's create a simple plugin called makeGreen() that turns the text color of
any element to green.
// 1. Define the plugin
jQuery.fn.makeGreen = function() {
// 'this' refers to the set of elements in the collection
return this.css("color", "green");
};
// 2. Use the plugin
$("p").makeGreen();
In standard jQuery, you can do this: $("p").hide().fadeIn();. This is
possible because every method returns the jQuery object. Your plugin should do the same.
jQuery.fn.highlight = function() {
this.css("background-color", "yellow");
return this; // Crucial for chaining!
};
// Now you can chain it:
$("span").highlight().fadeOut("slow");
this **already is** a jQuery object. You don't need to write
$(this) yet. You only use $(this) when you are inside a loop
like this.each().
If you need to perform custom logic for every element in a selection, use the
each() method inside your plugin block.
jQuery.fn.showDimensions = function() {
return this.each(function() {
// Now 'this' is a DOM element, so we wrap it
var width = $(this).width();
var height = $(this).height();
$(this).append(" <span>(" + width + "x" + height + ")</span>");
});
};
jquery.[pluginname].js. For example, a plugin named "superGallery" should be
in a file called jquery.supergallery.js.