jQuery plugins are reusable JavaScript modules that extend jQuery’s functionality. They allow developers to add complex behavior such as sliders, modals, form validation, animations, and AJAX helpers using simple method calls.
$.fn objectthisA jQuery plugin is created by attaching a function to $.fn. Inside the function, this refers to the current jQuery object.
// Basic structure of a jQuery plugin
(function($){
$.fn.myPlugin = function(){
return this.each(function(){
// Plugin logic goes here
});
};
})(jQuery);
The following example creates a simple plugin that highlights selected elements.
// Custom jQuery plugin to highlight elements
(function($){
$.fn.highlight = function(color){
return this.each(function(){
$(this).css("background-color", color || "yellow");
});
};
})(jQuery);
When $("p").highlight("lightblue") is called, all paragraph elements receive a light blue background color using the custom plugin.
Click the button below to apply a jQuery plugin effect.
// Using the custom highlight plugin on button click
$("#demoBtn").on("click", function(){
$("h2").highlight("#fde68a");
});
this to maintain chaining$.extend()