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.

Wednesday, April 11, 2012

Why to and How use to jQuery?

        Here I will talk about jQuery, a very useful javascipt library. I will tell you why to use jQuery and how to use jQuery.
First and very important thing about jQuery , that even you will find first on jquery.com, is that it is NOT a programming language but simply a JavaScript Library.
If you want to use it, just go to their site and download appropriate .js file. You can download either production version or Development one for you. See which one suits for you...
  •   Production Version is lesser in size, but its content is not readable so you almost can't modify it. If you don't want to modify it, use this version, as this will reduce page load time. This will have "min" it's .js file name.
  • Development version is quite larger in size and in editable format. So on other way if you want to modify this, you will go for this version.

Why to jQuery?

There are five main reasons for selecting jQuery.
  1. It is simple to use. We need to write less code and it does more(as they say).
  2. Great support from forums and easy documentation.
  3. Ajax support.
  4. jQueryUI can be used very easily to develop very good User Interface Components.
  5. Large very large actually, Number of Plugins are available, that would help you do lot more things in easy way. Plugins are available from simple ToolTip plugins to complex Image Viewer to Great Menu Structures.
And i have stated these reasons in ascending order of importance...
Plugins are very useful, you will thank them a lot when you will be in need..

How to jQuery ?

After going through why to use jQuery let's see how to use jQuery.
The basic syntax for jQuery Statement is 
 $(Selector).event();
As this is javaScript library , all jQuery lines comes under 
<Script>
</Script> tag or separate .js file.

It is always safe to write jQuery code under following function
$(document).ready(function(
{
//code here
}));
this is also jQuery statement, meaning, execute following code only after document is ready means document's DOM structure is ready.
This ready is different than onload function of javascript, ready is when whole DOM structure of HTML document is ready, and onload is when entire content, including all images on the page, is loaded in the browser.
Main purpose of jQuery is to travel through elements on the page, assign some event handlers for them and perform some action on them.


Selectors :

There are many selectors of different form,
  • Few allow you to select elements by their attributes, those of [] form.
  • Select multiple elements.
  • Select by class or id value.
  • Few of ":" type allow you to filter the set by some way like for example :first would select first element of the preselected set of elements.
  • Few playing with parent child relationships.

Events :

Events allow you to subscribe some event handles for some of the event types on some elements. Events like .click(),  .mouseover() , .focus(),  keydown() are handy.
Also there are many methods to bind particular even customized events with handlers like .bind(type , data , function), on(type,selector,data,function)  etc.



Effects :

There are many methods to apply great variety of effects to selected elements.
Ex. .css(attributes) allow you to change css properties of the elements.
.addClass(class),  .toggleClass(class)
.show()  ,  .hide(speed)
.slideDown()
.animate()
.fadeIn()  ,  .fadeOut().
and many more, and many with overloaded forms with different parameters.

Manipulation :

There are many ways you can manipulate the elements and contents of them.
Ex. .append(content) 
.after(content)
.wrap(html)
.replaceWith(content)
.empty()
.clone()

Traversing :

Few of them allow you to travel through the documents with some relations. Like for example 
.parent()    .nextAll()   .each(f)  .children() etc.

Ajax :

There is great deal of support for ajax in jQuery. At this point it's adequate to just know that it DOES support ajax with methods like.
.ajaxComplete(c)
.ajaxStart(c)
$ajax( options ) etc.


And don't forget this one jQuery Complete Cheat Sheet .