Creating a jQuery plugin allows you to extend jQuery’s functionality by adding reusable methods that can be applied to selected elements. Plugins help keep code modular, reusable, and easy to maintain.
$.fnthis refers to the jQuery-selected element$.extend()A basic jQuery plugin structure attaches a function to $.fn. This makes it accessible to any jQuery object.
// Basic structure of a jQuery plugin
(function($){
$.fn.myPlugin = function(){
return this.each(function(){
$(this).css("color","blue");
});
};
})(jQuery);
This example creates a plugin that highlights elements with a custom background color.
// Custom highlight plugin with options
(function($){
$.fn.highlightBox = function(options){
var settings = $.extend({
color: "yellow",
padding: "10px"
}, options);
return this.each(function(){
$(this).css({
backgroundColor: settings.color,
padding: settings.padding
});
});
};
})(jQuery);
When highlightBox() is called on a jQuery element, the plugin applies background color and padding based on provided options or defaults.
Click the button below to apply the custom plugin to the box.
// Applying the plugin interactively
function applyPlugin(){
$("#demoBox").highlightBox({
color: "#93c5fd",
padding: "20px"
});
}
this for chaining$.extend() for configurable options.animate()