jQuery is the most popular JavaScript library and many sites adopt it for dynamic effects and Ajax functionality. However, relatively few developers delve into the depths of plugin development.Why a plugin?
First of all, you might ask yourself why you'd want to develop a plugin. The first and best reason is the ability to maintain chainability. When people ask me the best feature of jQuery, I'd probably mention the chainability. It allows you do do things like:
Code:
$('.className').addClass('enabled').append('Click here').click( func ); This would take every element with a class name of 'className', add a new class name to it, append some HTML, and set a click event handler. When you develop a plugin, you have the ability to intject your own functionality while still maintaining the chain.Another reason to develop a jQuery plugin is simply to be consistent with the jQuery ethos. The jQuery ethos, in my opinion, is that the HTML element is king (or queen — lest I be mysoginistic about my HTML elements). It's all about getting elements and then performing actions on those elements.Now, let's take a look at how to create a plugin, of which there are two possible approaches.
Approach 1: The Function
jQuery.log = function(message) { if(window.console) { console.debug(message); } else { alert(message); } };
In this example, a log function has been attached to the jQuery object. You can then call this in your code using jQuery.log('my message')
or $.log('my message')
. There's no chainability or HTML elements involved (unless you add that into your code).
Approach 2:
jQuery.fn.newMethod = function(){ return this; }
The this
keyword refers to the current jQuery object. You'll have access to jQuery's methods and functions. If you need to perform an action on each element then you can do something like this:
jQuery.fn.newMethod = function(){
return this.each(function(){
alert(this);
});
}
The this
keyword within the inner function refers to the current HTML element, which won't have access to the jQuery methods (although, it's as easy as wrapping it in the jQuery object to get those methods back).
Don't use $
When developing a plugin, you'll want to avoid using the familiar dollar function, $, to avoid any conflicts. jQuery has a no-conflict mode for turning the alias on and off. If you want, you can alias the jQuery function within your plugin. It'll be self-contained and avoid any outside conflicts.