Introduction
First and far most, we should say thanks to John Resig and his team to make our life so easier then before by making jQuery, most demanding and powerful JavaScript framework and it’s expanding phenomenally that gives the proof of dominancy of jQuery framework.
Why jQuery
So why do I need to extend jQuery?
Here we go; no library is full filling all the requirements so does jQuery, so there should be some mechanism to add sets of useful methods called as plugins for your specific requirement, which we can say in the basic terminology calling your external methods into your structure but it doesn’t give you the power of leverage existing code base.
Let’s say, by creating a new jQuery commands, we automatically inherit the use of powerful selector mechanism and can use all the jQuery methods and indeed it’s a good practice to make reusable code.
There is a pretty good documentation and guidelines available on jQuery Plugins/Authoring page.
Step1
Let’s start making our first jQuery plugin; we call our plugin as “disable”, we make our plugin to disable the form elements and then we will extend our default options using $.extend utility method to enable the required once and will add a toggle method also.
We will follow the guidelines as provided on jQuery.com so we will save our plugin as jquery.disable.js
[sourcecode language=’js’]
// plugin definition
$.fn.disable = function() {
// plugin implementation code goes here.
};
[/sourcecode]
$.fn.disable means that we are extending the $ wrapper with a function called disable.
Step2
Let’s wrap into self executed anonymous function and will pass out jQuery alias in the parentheses, why it so, it’s because of author may have used $.noConflict() after using this technique there will not be any conflict between other library.
[sourcecode language=’js’]
(function($) {
$.fn.disable = function(){
// plugin implementation code goes here.
})(jQuery)
[/sourcecode]
Now we extend our default options because we will be using the same method to enable the disabled once.
Our plugin invoke code goes like this with native jquery framework and plugin call:
[sourcecode language=’html’]
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
[/sourcecode]
We are using attribute filter here, which will find out all input elements with a type of text on the page and then it will disable all the input elements.
Step3
So far so good; you can further look into http://www.learningjquery.com/2007/10/a-plugin-development-pattern which gives more insight about plugin development.
[sourcecode language=’js’]
(function($) {
$.fn.disable = function(options){
// plugin defaults
var defaults = {
disabled: true
};
// Extend our default options with those provided.
var opts = $.extend({}, defaults, options);
return this.each(function(){
})
})(jQuery)
[/sourcecode]
$.extend() extend one object with one or more others, returning the original, modified, object. This is a great utility for simple inheritance.
Then the each() method is called to iterate over each element in the wrapped collection and return the same, inside that function, this is the collection of wrapped DOM elements that needs to be operated upon.
There is a pretty good reference on http://www.visualjquery.com/ about all the jQuery API reference in a nice format compare to http://docs.jquery.com/
Step4
Now we are pretty close to it.
[sourcecode language=’js’]
(function($) {
$.fn.disable = function(options){
// plugin defaults
var defaults = {
disabled: true
};
// Extend our default options with those provided.
var opts = $.extend({}, defaults, options);
return this.each(function(){
if(typeof this.disabled != ‘undefined’)
this.disabled = true;
})
}
})(jQuery)
[/sourcecode]
We just try to find out each and every html element disabled attribute, if it does exist then set it true.
We return the results of the each() method (the wrapper) so that our brand new disable() method will support chaining like many of the native jQuery methods. We’ll be able to write
[sourcecode language=’js’]
$(“input[type=text]”).disable().addClass(“blink”);
[/sourcecode]
We are done with the disable functionality now just make it configurable so that we can enable the elements when needed.
Just change the call and place disabled: false as parameter which indeed over write the default option, which is set true initially.
[sourcecode language=’js’]
$(function(){
$(“input[value=Enable]”).click(function(){
$(“input[type=text]”).disable({disabled: false})
});
});
[/sourcecode]
We just need to make a small check; we are checking disabled parameter value in if condition which is set false in the current scenario then it goes into the else part which enables our disabled elements.
Step 4
We can further enhance our plugin; let’s extend another method which will toggle the disable state, its pretty straight forward, we just reduced our code using ternary operator instead of making 4 lines of code.
We just checking disabled attribute to true, if it’s then set it to false other wise disabled it.
[sourcecode language=’js’]
$.fn.extend({
disableToggle: function() {
return this.each(function(){
this.disabled = this.disabled == true ? false : true;
})
}
})
[/sourcecode]
Plugin code:
[sourcecode language=’js’]
(function($) {
$.fn.disable = function(options){
// plugin defaults
var defaults = {
disabled: true
};
// Extend our default options with those provided.
var opts = $.extend({}, defaults, options);
return this.each(function(){
if(typeof this.disabled != ‘undefined’ &amp;&amp; opts.disabled != false){
this.disabled = true;
} else {
this.disabled = false;
}
})
}
//Prototype Methods: extending it with check, uncheck, disableToggle
$.fn.extend({
disableToggle: function() {
return this.each(function(){
this.disabled = this.disabled == true ? false : true;
})
}
})
})(jQuery)
[/sourcecode]
HTML code:
[sourcecode language=’xhtml’]
< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
HTML Form
[/sourcecode]
We are done with the very first plugin of yours, there are whole lots of opportunities to improve and shorten your code, and we can further enhance it but it is just a reference to give you a heads up about one of the power full feature of jQuery framework, of course you should unit test your code also.
If you have questions, enhancement anything related to this plugin just write your thoughts.
Thanks for reading!
10 Comments
Add comment
This site uses Akismet to reduce spam. Learn how your comment data is processed.
A gud one…keep the gud work going arif 🙂
Cheers,
Ranji
Hey mohammed.
Its always great to see people contributing back. This article is a great start-up guide to writing jQuery Plugins!
Cheers.
Brilliant Article!!!
Keep up the good work man.
–Kumar Amit Ranjan
Gr8 blog on JQuery Plug in.
Kep it up………
Note: JQuery is going to be part of dot net framework 4.0 in future
Awesome!!
Code block are presented in a very neat manner.
Awesome!! Simple. Keep going…
Though not a big deal,
Under “plugin code” section, both return statements not ended with semicolon.
@ raja – semicolon doesn’t impact the code unless until you packed your JS using some JS packer.
Practically speaking, semicolons are not needed in most cases. The browser can usually parse statements based on new-lines, line-breaks and other informal conventions.
But it’s always good to have it to avoid any JavaScript code confusion.
Nice tutorial, good reading.
Nice piece of work
But cant line 4 of disableToggle method be like this?
this.disabled = !this.disabled;
Thanks Pramod
You are right, that’s shorter version of that ternary statement but done that deliberately, just wanted to kept it simple to understand for novice JavaScript/jQuery developers.