Ways to write your own jQuery Plugin
If you want to extend jQuery element collection, like:
$("input[type=checkbox]").check();
$("input[type=radio]").uncheck();
Then you can do like this:
jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});
If you want to add methods for jQuery namespace, like:
jQuery.min(2,3); // => 2 jQuery.max(4,5); // => 5You can do like this:
jQuery.extend({
min: function(a, b) { return a < b ? a : b; },
max: function(a, b) { return a > b ? a : b; }
});
But in case of doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign.so it can't be overwritten by another library in the scope of its execution.
(function( $ ) { $.fn.myPlugin = function() { // Do your awesome plugin stuff here }; })( jQuery );Best practices:
- Always wrap your plugin in a closure: (function( $ ){ /* plugin goes here */ })( jQuery );
- Don't redundantly wrap the this keyword in the immediate scope of your plugin's function
- Unless you're returning an intrinsic value from your plugin, always have your plugin's function return the this keyword to maintain chainability.
- Rather than requiring a lengthy amount of arguments, pass your plugin settings in an object literal that can be extended over the plugin's defaults.
- Don't clutter the jQuery.fn object with more than one namespace per plugin.
- Always namespace your methods, events and data.
- jQuery.fn is pronounced jQuery effin'