Monday, November 28, 2011

How to write jQuery plugin

Apart from offering a simple, effective, way to manage elements and various scripts, jQuery also offers a mechanism for adding methods and extra functionalities to the core module. By using this mechanism we are also allowed to create a new portion of the code and add reuse it in different pages and projects.

Write your first jQuery plugin


To write a plugin, Add new property in the jQuery.fn object where the name of the property will be the name of your plugin.
(function( $ ) {
  $.fn.myPlugin = function() {
  
    // Do your awesome plugin stuff here

  };
})( jQuery );

    
Lets start adding functionality with in your plugin and use it in web pages. In our first example, I will simply fadeout the element.
(function ($) {

    $.fn.myPlugin = function () {       

        this.fadeOut('normal');

    };
})(jQuery);


Now save the file with name “jquery-myPlugin.js” and your plugin is ready to use. Create html button and div on your page. Div will fade out on the click of the button.
<div style="border: 1px dotted gray; height: 75px; margin: auto; padding: 5px; width: 400px;">
   <div id="myDiv" style="padding: 6px; background-color: Silver;">
        I am div which need to be fade out;
    </div>
    <input id="btnFadeout" type="button" value="Fade out" />
 </div>
    
Now add jQuery script file ‘jquery-1.6.2.min.js’ and your plugin file ‘jquery-myPlugin.js’ into the page.
<script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-myPlugin.js"></script>
<script type="text/javascript">
    $(document).ready(function () {

        $("#btnFadeout").click(function () {
            $("#myDiv").myPlugin();
        });

    });
</script>

Register the click event of the button ‘btnFadeout’ button and call plugin method for ‘myDiv’ using $("#myDiv").myPlugin(); statement.

Plugin for muliple elements


You can also write plugin which performs action on the group of element. Suppose we want to change the background color of the element on mouse over. Simply get each element and register hover event for that object. Let’s start the code for hover plugin.
(function ($) {

    $.fn.hoverElement = function () {

        this.each(function () {

            $(this).hover(
                            function () {
                                $(this).addClass('hoverTextSel');
                            },
                            function () {
                                $(this).removeClass('hoverTextSel');
                            }
                        ); // end of Hover event

        }); // end for each

    }; // end of functions

})(jQuery);
    

$(selector).each() method is used to iterate over a jQuery object, array or any collection. This example registers the hover event for the each element of jQuery object.
<div style="width: 400px; margin: auto; padding: 5px; border: 1px dotted gray;">
    <div class="hoverText">
        First Button..
    </div>
    <div class="hoverText">
        Second Button..
    </div>
    <div class="hoverText">
        Third Button..
    </div>
</div>

In the html page, create buttons using div and assign ‘hoverText’ css class.
    $(".hoverText").hoverElement();
Now it is time to call the hoverElement() method for the collection. Select elements having css class ‘hoverText’ using jQuery selector ‘$(".hoverText") and call the method.

Chainability


The beauty of the jQuery’s design is, it maintains chainability. You can perform multiple actions in one series. So to maintain the chainability in a plugin, you must make sure your plugin returns the ‘this’ keyword
 (function ($) {

    $.fn.hoverElement = function () {

      return  this.each(function () {


          $(this).hover(
                            function () {
                                   $(this).addClass('hoverTextSel');
                            },
                            function () {
                                    $(this).removeClass('hoverTextSel');
                            }
                        ); // end of Hover event

        }); // end for each

    }; // end of functions

 })(jQuery);
 
Now you can perform multiple actions in one series.
  $(".hoverText2").hoverElement().css({'color':'red'});