Saturday, April 21, 2012

How to create your own jQuery plugin !

Once you know jQuery, it’s simple to create your own plugin. Depending on the complexity of your plugin, you need to take care of following steps. For learning purpose it’s good to go step by step and know why do we do what we do for creating your own plugin.

1. Cross Library Safety :

(function($){

//Here $ means jQuery

})(jQuery)

This will mean $ in that particular function is jQuery, so that there will be no conflict when you or someone else is using your jQuery plugin along with other java script libraries which may use $ for their own purpose.

2.Adding function property to the jQuery.fn object :

Here you will add your plugin to $fn object as a property which makes your plugin usable. Use your plugin name here.

(function( $ ) {
  $.fn.myPlugin = function() {
  
    //your plugin stuff here

  };
})( jQuery );

3.this is a  available object :

this variable  is available directly inside your function code so …
 this.fadeIn() works here, 
so no need to use $(this) for simple plugins.

4.Better use each to iterate over elements given by Selector :

this.each(function() {
        ///Some code here
    });
so that the selector on which your plugin is called when selects multiple elements, this will get applied to all of them.

5.To maintain chainability the plugin should return this keyword :


return this.each(function(parameters) {
         var $this = $(this);
      //code using $this 
    });

So hence forth you will be using $(this), through say variable $this.
Chainability allows to perform some actions on the same element(s) one by one, which simplifies the way your plugin would be used.



6. Multiple options with default values :

For more complex plugins providing multiple attributes, it’s better to provide default values for attributes..

(function( $ ){

  $.fn.tooltip = function( options ) {  
    // Create some defaults, extending them with any options that were provided
    var settings = $.extend( {
      'location'         : 'top',
      'background-color' : 'blue'
    }, options);

    return this.each(function() {        
//use settings[“location”]  or settings.location
      // Tooltip plugin code here
    });
  };
})( jQuery );

Calling it

$('div').tooltip({
  'location' : 'left'
});

 So if you have provided default options, you can use those in your code, now it's not necessary for user to provide values for all the attributes.

Here $.extend is used which accepts two object, here first one will be default values object and second one will be one provided by the user with his values. $.extend will merge second object into first, so that if values for some options are not provided then it will take default ones.

7.Multiple Methods in plugin with NAMESPACING :

(function( $ ){

  var methods = {
    init : function( options ) { 
      // code
    },
    show : function( ) {
      // code    },
    hide : function( ) { 
      // code
    },
    update : function( content ) { 
      // code    }
  };

  $.fn. myPlugin = function( method ) {
    
    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
  
  };

})( jQuery );

// calls the init method
$('div'). myPlugin (); 

// calls the init method
$('div'). myPlugin ({
  foo : 'bar'
});

Call these methods by first passing the string name of the method, and then passing any additional parameters you might need for that method. This type of method encapsulation and architecture is a standard in the jQuery plugin .

Calling this,

$('div'). myPlugin ('hide'); 
$('div'). myPlugin ('update', 'This is the new myPlugin content!'); 

8.Bind an event :
If you want your plugin to bind an event, use following way (please namespace it )
And have a method like destroy as shown below to unbind what is "bind" earlier.

init : function( options ) {

       return this.each(function(){
         $(window).bind('resize.myPlugin', methods.reposition);
       });

     },
     destroy : function( ) {

       return this.each(function(){
         $(window).unbind('. myPlugin ');
       })

     },
     reposition : function( ) { 
       // ... 
     },
$('#fun'). myPlugin ();
// Some time later...
$('#fun'). myPlugin ('destroy');


So now decide on your plugin idea and start writing it.
Best of Luck.

No comments:

Post a Comment