Writing a jQuery Plugin
Extend $.fn (which is jQuery.prototype) to add a method available on all jQuery objects. Always return this to maintain chainability.
Extend $.fn (which is jQuery.prototype) to add a method available on all jQuery objects. Always return this to maintain chainability.
$.fn.highlight = function(color) {
return this.each(function() {
$(this).css("background-color", color || "yellow");
});
};
// Usage — chainable
$("p.important").highlight("lightblue").addClass("highlighted");
Always return this.each(...) from plugins — it preserves jQuery chaining.