Chapter 8 Plugins
Use the $ alias when constructing a plugin
When writing a jQuery plugin, the same conflict prevention routine used with regular, old jQuery
code should be implemented. With this in mind, all plugins should be contained inside a private
scope where the $ alias can be used without fear of conflicts or surprising results.
The coding structure below should look familiar as it is used in almost every code example in
this book and explained in Chapter 1.
Sample: sample82.html
New plugins attach to jQuery.fn object to become jQuery methods
New plugins are attached to the jQuery.fn object, as this is a shortcut or alias for
jQuery.prototype. In our coding example below, we are adding the count plugin to the
jQuery.fn object. By doing this, we are creating our own custom jQuery method that can be
used on a wrapped set of DOM elements.
Basically, a plugin attached to jQuery.fn allows us to create our own custom methods similar
to any found in the API. This is because when we attach our plugin function to jQuery.fn, our
function is included in the prototype chain—$.fn.count = function(){}—for jQuery objects
created using the jQuery function. If that blows your mind, just remember that adding a function
to jQuery.fn means that the keyword this inside of the plugin function will refer to the jQuery
object itself.
84