Loading...
X

Build your first jQuery plugin

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

// plugin definition
$.fn.disable = function() {
 	// plugin implementation code goes here.
};

$.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.

(function($) {
	$.fn.disable = function(){
	// plugin implementation code goes here.
})(jQuery)

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:

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Extending jQuery</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery.disable.js"></script>
<script type="text/javascript">
$(function(){
	$("input[type=text]").disable();
});
</script>
</head>

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.

(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)

$.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.

(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)

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

$("input[type=text]").disable().addClass("blink");

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.

$(function(){
	$("input[value=Enable]").click(function(){
		$("input[type=text]").disable({disabled: false})
	});
});

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.

$.fn.extend({ 
	disableToggle: function() {
		return this.each(function(){
			this.disabled = this.disabled == true ? false : true;
		})
	}
})

Plugin code:

(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;amp;&amp;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) 

HTML code:

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</html><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Extending jQuery</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery.disable.js"></script>
<script type="text/javascript">
$(function(){
	$("input[type=text]").disable();
	$("input[value=Enable]").click(function(){
		$("input[type=text]").disable({disabled: false}) //enable them
	});
});
</script>
</head>
<body>
 <h1>HTML Form</h1>
    <fieldset>
      <legend>Form</legend>
      <div>
        <form id="testForm" action="">
          <div>
            <label>First Name:</label>
            <input type="text" name="text" class="fields" value="Mohammed"/>
          </div>
          <div>
            <label>Last Name:</label>
            <input type="text" name="text" class="fields" value="Arif"/>
          </div>

          <div>
            <label>Dropdown:</label>
            <select name="dropdown">
              <option>One</option>
              <option>Two</option>
              <option selected="selected">Three</option>
              <option>Four</option>
              <option>Five</option>
            </select>
          </div>

          <div>
            <label>Check box group:</label>
            <input type="checkbox" name="cb" value="cb.1"/>One
            <input type="checkbox" name="cb" value="cb.2" checked="checked"/>Two
            <input type="checkbox" name="cb" value="cb.3"/>Three
          </div>

          <div>
            <label>Radio group:</label>
            <input type="radio" name="radio" value="radio.1"/>One
            <input type="radio" name="radio" value="radio.2" checked="checked"/>Two
            <input type="radio" name="radio" value="radio.3"/>Three
          </div>

          <div>
            <label>Text area:</label>
            <textarea name="textarea" rows="5" cols="20"></textarea>
          </div>

          <div>
    <input type="button" value="Enable" />
          </div>
        </form>
      </div>
    </fieldset>
</body>
</html>

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 observations on “Build your first jQuery plugin
  1. Rukhsar Ahmad

    Gr8 blog on JQuery Plug in.
    Kep it up………

    Note: JQuery is going to be part of dot net framework 4.0 in future

     
  2. rajakvk

    Awesome!! Simple. Keep going…

    Though not a big deal,
    Under “plugin code” section, both return statements not ended with semicolon.

     
  3. Mohammed Arif

    @ 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.

     
  4. Pramod N

    Nice piece of work

    But cant line 4 of disableToggle method be like this?

    this.disabled = !this.disabled;

     
  5. Mohammed Arif

    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.

     

Leave Your Observation

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>