A jQuery plugin is a way of extending the jQuery framework with your own custom methods. It works by extending jQuery’s prototype object which allows your methods to be inheritable and accessible via the jQuery object.
This allows you to harness the power of jQuery by making your method available from the jQuery object itself. Let’s look at a quick example of creating one method by adding it to $.fn. This is shorthand for the jQuery prototype. The example in Listing 1-1 shows a method named colorCode that extend the jQuery prototype object.
$.fn.colorCode = function (term, cssClass) { var html = this.filter(":contains('" + term + "')").html().replace("" + term + "", "" + term + ""); return this.filter(":contains('" + term + "')").html(function () { return html; }); };
This allows me to use the jQuery selector to find all the li’s in my markup and apply my custom method to them.
$("li").colorCode("using", "blue_text");
Now we have extended jQuery with a custom method. But we are not quite done yet. If you are accustomed to using the $ alias as I am then there is one more step to take in order to prevent conflicts with other plugins so that we can keep using the $. Basically we are wrapping our method a method that passes the jQuery object with a named parameter of $. This is a recommended practice and accomplished by putting your code inside this block listed here.
The end result is an unordered list with the keyword “using” in blue:
And the complete code for this example in Listing 1-3.
(function ($) { $.fn.colorCode = function (term, cssClass) { var html = this.filter(":contains('" + term + "')").html().replace("" + term + "", "" + term + ""); return this.filter(":contains('" + term + "')").html(function () { return html; }); }; } (jQuery));