jQuery Plugins
jQuery plugins extend jQuery with reusable UI or utility features. A plugin is usually a function attached to $.fn, letting you call it like $('.box').myPlugin() and chain with other jQuery methods.
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Basic plugin | Attach a function to $.fn, iterate with return this.each(...). |
$.fn.hello = function(){ return this.each(...); } |
| Options & defaults | Merge user options with defaults via $.extend. |
var cfg = $.extend({}, defaults, opts) |
| Chaining / methods | Return this from setters to allow chaining; expose methods via data. |
return this; // enables $('#x').p().addClass('y') |
State via $.data() |
Store instance/state on elements to reuse across calls. | $el.data('pluginName', instance) |
| Events & namespacing | Use custom events and namespaced handlers for clean binds. | $el.on('click.plugin', ...), $el.trigger('plugin:change') |
| Destroy / cleanup | Support a 'destroy' command to unbind and remove state. |
if(cmd==='destroy'){ off, removeData, revert } |
noConflict() |
Avoid $ collisions with other libs; use alias. |
var jq = jQuery.noConflict(true) |
Tip: Keep plugins idempotent: calling it twice shouldn’t double-bind handlers. Use a data-flag to guard initialization.
1) Basic Plugin Pattern
// IIFE to avoid globals
(function($){
$.fn.hello = function(){
return this.each(function(){
$(this).append(' — from plugin');
});
};
})(jQuery);
2) Options & Defaults
var defaults = { text: 'Saved!', bg: '#4caf50' };
$.fn.toast = function(opts){
var cfg = $.extend({}, defaults, opts);
return this.each(function(){ /* use cfg */ });
};
3) Methods & Chaining
function Animator($el){ this.$el=$el; }
Animator.prototype.move=function(px){ this.$el.animate({left:"+="+px},200); return this; };
4) State with $.data()
$.fn.counter=function(){
return this.each(function(){
var $el=$(this);
$el.data('count', 0);
});
};
5) Custom Events & Namespacing
$.fn.toggler=function(){
return this.each(function(){
var $el=$(this);
$el.on('click.toggler', function(){
$el.toggleClass('on');
$el.trigger('toggler:change', [$el.hasClass('on')]);
});
});
};
6) Destroy / Cleanup Pattern
$.fn.clickable=function(cmd){
if(cmd==='destroy'){ // unbind + remove state }
return this.each(function(){ /* init once */ });
};
7) noConflict() & Using an Alias
var jq = jQuery.noConflict(true);
(function($){ // use $ safely here })(jq);
Production tip: Prefix your event namespaces (e.g.,
.sonuToggle) and export a documented API: init, methods (enable(), disable()), and destroy(). Avoid leaking globals.