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'}); 


Sunday, August 28, 2011

Selectors in JQuery

JQuery provides a simple way to select single element or group of elements. You can access element by type (div, span, p), id, CSS class and attribute etc.

Basic Selector


JQuery

Example Code

Description

Action

Output

$('element')

$('blockquote').css('color','red');

it select all elements with the give tag name. in this example it will return all
<blockquote> elements in the document.




Here is example text for the first selector example.


Here is second block quote text...


$('#id')

$('#item1').css('color','red');

it select single element with the give id. if more than one element has been assigned
same id, first match result will be return.



First line inside the <span id="item1" >


Second line inside the <span id="item2" >


First line inside the <span id="item1" >



$('.class')

$('.myCss').css('color','red');

it select all the elements with given class.



First line for testing.


Second line for testing.




Basic Filters


JQuery

Example Code

Description

Action

Output

:first

$('#basicList li:first').css('background-color','yellow');

:first selects the first matched element. '#basicList li:first' selects the first
element of list.




  • Item 1

  • Item 2

  • Item 3

  • Item 4

  • Item 5

  • Item 6

  • Item 7



:last

$('#basicList li:last').css('background-color','red');

:last selects the last matched element. '#basicList li:last' selects the last element
of list.



:not(selector)

$('#basicList li:not(li:first)').css('background-color','pink');

:not(selector) selects all elements that do not match the given selector. '#basicList
li:not(li:first)' selects all element other than first element.



:even

$('#basicList li:even').css('background-color','blue');

:even selects the even elements. it uses zero-indexed. so this command will select
first, third, fifth,..... so on.



:odd

$('#basicList li:odd').css('background-color','green');

:old selects the old elements. it also uses zero-indexed. So this command will select
second, fouth, sixth,..... so on.



:eq(index)

$('#basicList li:eq(3)').css('background-color','yellow');

:eq(index) selects the element at index n with in the set. this example code will
select 4th element in the list.



:gt(index)

$('#basicList li:gt(3)').css('background-color','red');

:gt(index) select all elements at an index grater than index number for filtering.



:lt(index)

$('#basicList li:lt(3)').css('background-color','purple');

:lt(index) select all elements at an index less than index number for filtering.



Filter By Content



Jquery

Example Code

Description

Action

Output

:contains(text)

$('#p1 span:contains(too)').css('background-color','yellow');

it selects all the <span> which contains word 'too'




Text in the span 1..... Text in the span 2 too



:empty

$('#list:empty').addClass('emptyUL');

:empty return those element who does not has child elements.



UL with no childs


UL with no childs

  • Child 1

  • Child 2




:has(selector)

$('#list2 li:has(a)').css('background-color', 'red');

The expression $('li:has(a)') matches a <li> if a <a> exists anywhere among
its descendants, not just as a direct child.




:parent

$('#table1 td:parent').css('background-color', 'red');

:parent is the inverse of :empty. :parent select those who has atleast one child
element.




Cell 1



Cell 4


Child Filters

:nth-child(index/even/odd/equation)


JQuery

Example Code

Description

Action

Output

:nth-child(even)

$('#Ul2 li:nth-child(even)').css('background-color', 'red');

....



List# 1

  • Item 1

  • Item 2

  • Item 3

  • Item 4

  • Item 5

  • Item 6

  • Item 7




List# 2

  • Item 1



:nth-child(odd)

$('#Ul2 li:nth-child(odd)').css('background-color', 'blue');

...



:nth-child(n)

$('#Ul2 li:nth-child(3)').css('background-color', 'yellow');

...



:nth-child(equation)

$('#Ul2 li:nth-child(3n)').css('background-color', 'yellow');

....



:first-child

$('#Ul2 li:first-child').css('background-color', 'purple');

....



:last-child

$('#Ul2 li:last-child').css('background-color', 'brown');

....



:only-child

$('#tdChildList li:only-child').css('background-color', 'gray');

....



Attribute Filters



JQuery

Example Code

Description

Action

Output

[Attribute Name]

$('#tdAtt a[id]').css('background-color','yellow');

select the elements that has specific attribue.



Click here 1

Click here 2

Click here 3

Click here 4


[AttributeName="value"]

$('#tdAtt a[rel="2"]').css('background-color','red');

Select the elements that has specific attribute with a value exactly equal to value.



[AttributeName!="value"]

$('#tdAtt a[rel!="2"]').css('background-color','brown');

Select the elements that has specific attribute with a value not equal to value.



[AttributeName^="value"]

$('#tdAtt a[href^="http://"]').css('background-color','blue');

Selects elements that have the specified attribute with a value beginning exactly
with a given string.



[AttributeName$="value"]

$('#tdAtt a[href$=".com"]').css('background-color','gray');

Selects elements that have the specified attribute with a value ending exactly with
a given string.



[AttributeName*="value"]

$('#tdAtt a[href*="www"]').css('background-color','pink');

Selects elements that have the specified attribute with a value containing the a
given substring.