A jQuery plugin is a reusable and extendable piece of code that you can attach to any jQuery object to add functionality. Creating your own plugin allows you to package and reuse functionality in a clean and modular way.
Basic Structure of a jQuery Plugin
(function($) {
$.fn.pluginName = function(options) {
// Default settings
var settings = $.extend({
option1: "default1",
option2: "default2"
}, options);
// Plugin logic
return this.each(function() {
// 'this' refers to the current DOM element
var $this = $(this);
// Example: Apply functionality
$this.text("Plugin activated with " + settings.option1 + " and " + settings.option2);
});
};
})(jQuery);
How the Plugin Works
- Immediately Invoked Function Expression (IIFE): Wraps the plugin in a function to avoid polluting the global namespace.
$.fn: Extends the jQuery object to add a custom method (pluginName).- Options and Defaults: Merge user-defined options with default settings using
$.extend(). this.each(): Iterates over all selected elements to ensure the plugin works on multiple elements.