Sometimes you want to make a piece of functionality available throughout your code; for example, perhaps you want a single method you can call on a jQuery selection that performs a series of operations on the selection. In this case, you may want to write a plugin.
Most plugins are simply methods created in the $.fn
namespace. jQuery guarantees that a method called on a jQuery object will
be able to access that jQuery object as this
inside the
method. In return, your plugin needs to guarantee that it returns the same
object it received, unless explicitly documented otherwise.
Here is an example of a simple plugin:
Example 8.1. Creating a plugin to add and remove a class on hover
// defining the plugin (function($){ $.fn.hoverClass = function(c) { return this.hover( function() { $(this).toggleClass(c); } ); }; }(jQuery); // using the plugin $('li').hoverClass('hover');
Copyright Rebecca Murphey, released under the Creative Commons Attribution-Share Alike 3.0 United States license.