jQuery Tutorial

1- Download jQuery

You have 2 options to download jQuery:
  • jQuery 1.x
  • jQuery 2.x
Both version are no differences in the API, jQuery 1.x support all browsers including IE 6,7,8; whereas jQuery 2.x supports all browsers except IE 6,7,8. Therefore you should consider version to the download. In this guide I downloaded version 1.x:
Download Results:

2- Hello jQuery example

Create examples folder, the examples in this document will be placed in this folder.
Declaring using jQuery library:
<!-- Declaring use jquery, specify the location of your jQuery library -->
<script type="text/javascript" src="../jquery-1.11.3.min.js"></script>

<!-- Or use external sources -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js">

</script>
When the web page is in the ready state, it means that the  document object  is in ready state, jQuery will catch this event by ready method.
// When the document is ready.
jQuery(document).ready(function(){
  alert('Hello jQuery');
});

// You can also use $ instead of jQuery.
$(document).ready(function(){
  alert('Hello jQuery');
});
Consider a simple example:
  • helloJQuery.html
<html>
<head>
    <meta charset="utf-8">
    <title>Hello jQuery Example</title>
    
    <!-- (1): Declaring using JQuery library -->
    <script src="../jquery-1.11.3.min.js"></script>
    
</head>
<body>
    <h2>Hello jQuery Example</h2>
    <a href="">Reset</a>
    
    <script type="text/javascript">
        
       jQuery(document).ready(function(){
           alert("Hello jQuery");
       });
    
    </script>
    
    
</body>
</html>
Running the example:

3- jQuery Selector

3.1- What is jQuery Selector?

An HTML page includes a lot of elements, Selector used to select the elements matching a criteria. For example select all of the <h1> in page, or all of the <div> in the page.

The concept of the Selector is one of the most important concepts of jQuery.

3.2- Example with Selector

The first example, select all of the div element in the document and set the border for it to " 1px solid red". Here we use the syntax:
// Select all <div> elements in HTML page.
jQuery('div')

// You can replace jQuery by $
$('div')
  • selector_tagname.html
<html>
<head>
   <meta charset="utf-8">
   <title>jQuery Select elements by tagName</title>
   
   <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
   
   <style>
      div {
        padding: 5px;
        margin:5px;
        width: 100px;
      }
   </style>
   
   <script>
      function selectDiv()  {  
          $('div').css("border","1px solid red");
      }    
   </script>
</head>
<body>

   <input type="button" onclick="selectDiv();" value="Select Div"/>
   <a href="">Refresh this page</a>
   
   
   <div>Div1</div>
   
   <h2>H2 tag</h2>
   
   <div>
       
        <div>Div3</div>
       
        <div>Div4</div>
   
   </div>
   
   
</body>
</html>
Running the example:
Selecting elements by class name.
Syntax:
// Select all elements has classname='abc'.
jQuery('.abc')

// You can replace jQuery by $
$('.abc')
  • selector_classname.html
<html>
<head>
   <meta charset="utf-8">
   <title>jQuery Select elements by classname</title>
   
   <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
   
   <style>
      h2, div {
        padding: 5px;
        margin:5px;
        width: 250px;
      }
   </style>
   
   <script>
      function selectByClassName()  {  
          $('.abc').css("border","1px solid red");
      }    
   </script>
</head>
<body>

   <input type="button" onclick="selectByClassName();" value="Select By ClassName"/>
   <a href="">Reset</a>
   
   
   <div>Div1</div>
   
   <h2 class='abc'>H2 with class='abc'</h2>
   
   <div>
       
        <div class='abc'>Div3 with class='abc'</div>
       
        <div class='abc'>Div4 with class='abc'</div>
   
   </div>
   
   
</body>
</html>
Running the example:

3.3- The syntaxs of Selector

Above, I have introduced a few examples of Selector, in this section I'll list out the different syntax of the Selector.
Selector Example Selects
* $("*") All elements
#id $("#lastname") The element with id="lastname"
.class $(".intro") All elements with class="intro"
.class,.class $(".intro,.demo") All elements with the class "intro" or "demo"
element $("p") All <p> elements
el1,el2,el3 $("h1,div,p") All <h1>, <div> and <p> elements
     
:first $("p:first") The first <p> element
:last $("p:last") The last <p> element
:even $("tr:even") All even <tr> elements
:odd $("tr:odd") All odd <tr> elements
     
:first-child $("p:first-child") All <p> elements that are the first child of their parent
:first-of-type $("p:first-of-type") All <p> elements that are the first <p> element of their parent
:last-child $("p:last-child") All <p> elements that are the last child of their parent
:last-of-type $("p:last-of-type") All <p> elements that are the last <p> element of their parent
:nth-child(n) $("p:nth-child(2)") All <p> elements that are the 2nd child of their parent
:nth-last-child(n) $("p:nth-last-child(2)") All <p> elements that are the 2nd child of their parent, counting from the last child
:nth-of-type(n) $("p:nth-of-type(2)") All <p> elements that are the 2nd <p> element of their parent
:nth-last-of-type(n) $("p:nth-last-of-type(2)") All <p> elements that are the 2nd <p> element of their parent, counting from the last child
:only-child $("p:only-child") All <p> elements that are the only child of their parent
:only-of-type $("p:only-of-type") All <p> elements that are the only child, of its type, of their parent
     
parent > child $("div > p") All <p> elements that are a direct child of a <div> element
parent descendant $("div p") All <p> elements that are descendants of a <div> element
element + next $("div + p") The <p> element that are next to each <div> elements
element ~ siblings $("div ~ p") All <p> elements that are siblings of a <div> element
     
:eq(index) $("ul li:eq(3)") The fourth element in a list (index starts at 0)
:gt(no) $("ul li:gt(3)") List elements with an index greater than 3
:lt(no) $("ul li:lt(3)") List elements with an index less than 3
:not(selector) $("input:not(:empty)") All input elements that are not empty
     
:header $(":header") All header elements <h1>, <h2> ...
:animated $(":animated") All animated elements
:focus $(":focus") The element that currently has focus
:contains(text) $(":contains('Hello')") All elements which contains the text "Hello"
:has(selector) $("div:has(p)") All <div> elements that have a <p> element
:empty $(":empty") All elements that are empty
:parent $(":parent") All elements that are a parent of another element
:hidden $("p:hidden") All hidden <p> elements
:visible $("table:visible") All visible tables
:root $(":root") The document's root element
:lang(language) $("p:lang(de)") All <p> elements with a lang attribute value starting with "de"
     
[attribute] $("[href]") All elements with a href attribute
[attribute=value] $("[href='default.htm']") All elements with a href attribute value equal to "default.htm"
[attribute!=value] $("[href!='default.htm']") All elements with a href attribute value not equal to "default.htm"
[attribute$=value] $("[href$='.jpg']") All elements with a href attribute value ending with ".jpg"
[attribute|=value] $("[title|='Tomorrow']") All elements with a title attribute value equal to 'Tomorrow', or starting with 'Tomorrow' followed by a hyphen
[attribute^=value] $("[title^='Tom']") All elements with a title attribute value starting with "Tom"
[attribute~=value] $("[title~='hello']") All elements with a title attribute value containing the specific word "hello"
[attribute*=value] $("[title*='hello']") All elements with a title attribute value containing the word "hello"
     
:input $(":input") All input elements
:text $(":text") All input elements with type="text"
:password $(":password") All input elements with type="password"
:radio $(":radio") All input elements with type="radio"
:checkbox $(":checkbox") All input elements with type="checkbox"
:submit $(":submit") All input elements with type="submit"
:reset $(":reset") All input elements with type="reset"
:button $(":button") All input elements with type="button"
:image $(":image") All input elements with type="image"
:file $(":file") All input elements with type="file"
:enabled $(":enabled") All enabled input elements
:disabled $(":disabled") All disabled input elements
:selected $(":selected") All selected input elements
:checked $(":checked") All checked input elements
The  above rules are the basic rules, you can combine them together.

Combining Selectors:

Rule:
  • $('div') - <div> elements.
  • $('.abc') - Elements with class='abc'.
  • $('#slider') - Element with ID is slider
Combine:
  • $('div.abc') - <div> elements with class='abc'.
  • $('div#slider') - <div> element with id ='slider'.

Rule:
  • $("p:first-child")  - <p> elements is first child of other element.
  • $('div') - <div> elements
  • $("div p") - The <p> elements are descendants of <div>
Combine:
  • $('div p:first-child') - The <p> elements is first child of <div> element.
Example:
  • selector_firstchildofdiv.html
<html>
<head>
   <meta charset="utf-8">
   <title>jQuery Select First child of div</title>
   
   <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
   
   <style>
      h2, div , p   {
        padding: 5px;
        margin:5px;
        width: 350px;
        border: 1px solid blue;
      }
   </style>
   
   <script>
      function selectAdv()  {  
          $('div p:first-child').css("background","#ccc");
      }    
   </script>
</head>
<body>

   <input type="button" onclick="selectAdv();" value="Select First Child of div"/>
   <a href="">Reset</a>
   
   
   <div>Div element</div>
   
   <h2 class='abc'>H2 element</h2>
   
   <div> Div element
       
        <p class='abc'>p - first child of div</p>
       
        <p class='abc'>p - second child of div</p>
       
        <div class='abc'> Div element
       
             <p>p -  first child of div</p>
             
        </div>
   
   </div>    
   
   
   <div>
       
        <div class='abc'>Div element</div>
       
        <p class='abc'>p - second child of p</p>        
   
   </div>    
   
</body>
</html>
Running the example:

4- jQuery Attribute

Each element on the page, with jQuery it will have the attributes, and methods that can be used.
For example, an element with attributes:
<!-- <a> element has two attributes href & target -->

<a href="abc.html" target="_blank">Abc.html</a>
jQuery provides you some methods to get the attribute value or set the value for the attribute

4.1- Getting attribute value

Method attr (name) of jQuery allows you to retrieve the value of the element's attributes:
  • attribute_getatt.html
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery - Get Attribute</title>
    
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
 
    
    <script>
    
       function getAttr()  {   
     
           // Get the href attribute value of the element with id = 'atag'
           var hrefValue = $('#atag').attr("href");
           
     
           // Set html to element with id='atag'.
           $('#atag').html(hrefValue);
       }    
    </script>
</head>
<body>
   <input type="button" onclick="getAttr();" value="Get Attribute"/>
   <a href="">Reset</a>
   
   <br><br>
   
   <a id="atag" href="http://jquery.com" target="_blank">jQuery</a>
    
</body>
</html>
Running the example:

4.2- Setting attribute values

Method attr (name, value) used to set values for attributes of element.
  • attribute_setatt.html
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery - Set Attribute</title>
    
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
 
    
    <script>
    
       function setAttr()  {   
      
           // Setting new value for the src attribute of the img elements.
           $('img').attr("src","images/jquery-mobile.png");
       }    
    </script>
</head>
<body>
   <input type="button" onclick="setAttr();" value="Set Attribute"/>
   <a href="">Reset</a>
   
   <br><br>
   
   <img src="images/jquery.png" > <img src="images/jquery2.png" >
    
</body>
</html>
Running the example:

4.3- Setting style

The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.
  • attribute_applystyle.html
<html>
<head>
   <meta charset="utf-8">
   <title>jQuery - Apply Style</title>
   
   <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>

   <style>
      .selected {color: red; }
      .highlight {background: yellow;}
   
   </style>
   
   <script>
   
      function applyStyle()  {  
          $('h1').addClass('selected highlight');
          $('h2').addClass('selected');
      }    
   </script>
</head>
<body>
  <input type="button" onclick="applyStyle();" value="Apply Style"/>
  <a href="">Reset</a>
 
  <br><br>
 
  <h1>H1 will apply selected + highlight</h1>
 
  <h2>H2 will apply selected</h2>
 
  <h1>H1 will apply selected + highlight</h1>
   
</body>
</html>
Running the example:

4.4- Attribute methods

S.N. Methods & Description Examples
1 attr( properties )

Set a key/value object as properties to all matched elements.

$('#id').attr('href')

$('a').attr({href:'a.html', alt:'a'})
2 attr( key, fn )

Set a single property to a computed value, on all matched elements.

$("table").attr("border", function(index) {
    return "1px";
})
3 removeAttr( name )

Remove an attribute from each of the matched elements.

$("table").removeAttr("border");
4 hasClass( class )

Returns true if the specified class is present on at least one of the set of matched elements.

$('h1').hasClass('highlight')
5 removeClass( class )

Removes all or the specified class(es) from the set of matched elements.

$('h1').removeClass('highlight')
6 toggleClass( class )

Adds the specified class if it is not present, removes the specified class if it is present.

$('h1').toggleClass('highlight')
7 html( )

Get the html contents (innerHTML) of the first matched element.

$('a').html()
8 html( val )

Set the html contents of every matched element.

$('a').html('Go to new page')
9 text( )

Get the combined text contents of all matched elements.

$('div').text()
10 text( val )

Set the text contents of all matched elements.

$('div').text('Text content')
11 val( )

Get the input value of the first matched element.

$("input").val();
12 val( val )

Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked.

$("input").val('New value');

5- DOM Traversing

5.1- What is Traversing?

jQuery traversing, which means "move through", are used to "find" (or select) HTML elements based on their relation to other elements. Start with one selection and move through that selection until you reach the elements you desire.
Consider an HTML document and it is transformed into a DOM structure (tree).
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery Traversing</title>
    
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
 
</head>
<body>

    <h3>jQuery Traversing</h3>
      
    <div>
        
         <ul>
            <li>Java</li>
            <li>.Net</li>
            <li>PHP</li>
         </ul>
    
    </div>     
    
</body>
</html>

5.2- jQuery Traversing - Ancestors

An ancestor is a parent, grandparent, great-grandparent, and so on.

With jQuery you can traverse up the DOM tree to find ancestors of an element.

jQuery has several methods allow you to move up (traverse up) higher DOM nodes (Ancetors).
  • parent()
  • parents()
  • parentsUntil()

5.2.1- parent()

The parent() method returns the direct parent element of the selected element.
For example, to find all the parent elements of the element have class = 'abc'.
  • traversing_parent.html
<html>
<head>
   <meta charset="utf-8">
   <title>jQuery Traversing - Parent</title>
   
   <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
   
   <style>
       div, ul, li { width: 200px;padding: 5px; margin: 5px; border: 1px solid blue;}
       .abc {border: 1px solid red;}
   </style>
   
   <script>
   
      function highlightParent()  {  
           
          $('.abc').parent().css("background","#ccc");
      }    
   </script>
   
</head>
<body>

   <h3>jQuery Traversing - parent </h3>
   <input type="button" onclick="highlightParent();" value="Highlight parent of element with class='abc'"/>
   <a href="">Reset</a>
       
   <div>
       
        <ul>
           <li class='abc'>li class='abc' </li>
           <li>li element</li>
           <li>li element</li>
        </ul>
   
   </div>    
   
   <div>
       <div class='abc'>Div class='abc'</div>
   </div>
   
</body>
</html>
Running the example:

5.2.2- parents

The parents() method returns all ancestor elements of the selected element, all the way up to the document's root element (<html>).
Ví dụ tìm kiếm tất cả các phần tử <div> là tổ tiên của phần tử có class= 'abc'.
  • traversing_parents.html
<html>
<head>
   <meta charset="utf-8">
   <title>jQuery Traversing - Parent</title>
   
   <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
   
   <style>
       div, ul, li { width: 200px;padding: 5px; margin: 5px; border: 1px solid blue;}
       .abc {border: 1px solid red;}
   </style>
   
   <script>
   
      function highlightParents()  {  
           
          $('.abc').parents('div').css("background","#ccc");
      }    
   </script>
   
</head>
<body>

   <h3>jQuery Traversing - parent </h3>
   <input type="button" onclick="highlightParents();" value="Highlight DIV ancestors of element with class='abc'"/>
   <a href="">Reset</a>
       
   <div>
       
        <ul>
           <li class='abc'>li class='abc' </li>
           <li>li element</li>
           <li>li element</li>
        </ul>
   
   </div>    
   
   <div>
       <div class='abc'>Div class='abc'</div>
   </div>
   
</body>
</html>
Running the example:

5.2.3- parentsUntil()

Mode of parentsUntil() returns all ancestor elements  between 2 elements include elements are selected and determined element in the parameter.
For example find ancestor elements of <h2> until caught the <div>:
  • traversing_parentsUntil.html
<html>
<head>
   <meta charset="utf-8">
   <title>jQuery Traversing - parentsUntil</title>
   
   <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
   
   <style>
       div, span, ul, li , h2 {padding: 5px; margin: 5px; border: 1px solid blue;}
   </style>
   
   <script>
   
      function highlightParentsUntil()  {    
          $('h2').parentsUntil('div').css("border","2px solid red");
      }    
   </script>
   
</head>
<body>

   <h3>jQuery Traversing - parentsUtil</h3>
   <p>$('h2').parentsUntil('div').css("border","2px solid red");</p>
   <input type="button" onclick="highlightParentsUntil();"
                   value="Highlight ancestors elements between H2 and DIV"/>
   <a href="">Reset</a>
       
   <div> div element
       
        <ul> ul element
                     
           <li>
              li element
              <h2>h2 element</h2>
           </li>
           
           <li>li element</li>
        </ul>
   
   </div>
   
</body>
</html>
Running the example:

5.3- jQuery Traversing - Descendants

Search the descendant elements of the selected elements (child, grandchild,...)
jQuery gives you 2 methods:
  • children()
  • find()

5.3.1- children()

The children() method returns all direct children of the selected element.
For example, highlighting the child elements of <div> elements.
  • traversing_children.html
<html>
<head>
   <meta charset="utf-8">
   <title>jQuery Traversing - children</title>
   
   <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
   
   <style>
       div, span, ul, li , h2 {padding: 5px; margin: 5px; border: 1px solid blue;}
   </style>
   
   <script>
   
      function highlightChildren()  {    
          $('div').children().css("border","2px solid red");
      }    
   </script>
   
</head>
<body>

   <h3>jQuery Traversing - children</h3>
   <p>$('div').children().css("border","2px solid red");</p>
   <input type="button" onclick="highlightChildren();"
             value="Highlight children of DIV"/>
   <a href="">Reset</a>
       
   <div> div element
       
        <h2>h2 element</h2>
       
        <ul>
           ul element
           
           <li>li element</li>
           <li>li element</li>
        </ul>
   
   </div>
   
</body>
</html>
Running the example:

5.3.2- find()

Find the appropriate element in the set of descendant element of the selected elements.
For example, searching the <h2> elements which is descendant of <div> elements
  • traversing_find.html
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery Traversing - find</title>
    
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
    
    <style>
        div,  h2 , ul, li {padding: 5px; margin: 5px; border: 1px solid blue;}
    </style>
    
    <script>
    
       function highlightFind()  {    
           $('div').find('h2').css("border","2px solid red");
       }    
    </script>
    
</head>
<body>

    <h3>jQuery Traversing - find</h3>
    <p>$('div').find('h2').css("border","2px solid red");</p>
    <input type="button" onclick="highlightFind();"
              value="Highlight descendants H2 of DIV"/>
    <a href="">Reset</a>
        
    <h2>h2 element</h2>
        
    <div> div element
        
         <h2>h2 element</h2>
         
         <ul>ul element
            <li>li element
               <h2>h2 element</h2>
            </li>  
            <li>li element</li>
         </ul>
    
    </div>
    
</body>
</html>
Running the example:

5.4- jQuery Traversing - Siblings

Search the sibling element, which has the same parent element with the current element.
jQuery provides you a number of searching methods of sibling elements.
  • siblings()
  • next()
  • nextAll()
  • nextUntil()
  • prev()
  • prevAll()
  • prevUntil()
nextUntil(..) & prevUntil(..):

5.4.1- siblings(), next(), prev(), nextAll(), prevAll(), nextUntil(), prevUntil example

Methods:
Method Description Example
siblings([selector]) The siblings() method returns all sibling elements of the selected element. $('h2').siblings()
next([selector]) The next() method returns the next sibling element of the selected element. $('h2').next()
prev([selector]) The prev() method returns the previous sibling element of the selected element. $('h2').prev()
nextAll([selector]) The nextAll() method returns all next sibling elements of the selected element. $('h2').nextAll()
prevAll([selector]) The prevAll() method returns all previous sibling elements of the selected element. $('h2').prevAll()
nextUntil(selector) The nextUntil() method returns all next sibling elements between two given arguments. $('h2').nextUntil('h4.blue')
prevUntil(selector) The prevUntil() method returns all previous sibling elements between two given arguments. $('h2').prevUntil('h1')
The following example illustrates the use of these methods:
  • siblings(), next(), prev(), nextAll(), prevAll(), nextUntil(), prevUntil().
  • traversing_siblings.html
<html>
<head>
   <meta charset="utf-8">
   <title>jQuery Traversing - siblings</title>
   
   <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
   
   <style>
     h1, h2, h4, p, div {padding: 5px; margin: 5px; border: 1px solid black;}
         h2 {border: 2px solid red;}
        .blue {border: 2px solid blue;}
   </style>
   
   <script>
      function clearAll() {
          $('h1, h2, h4, p, div').css("background","white");
      }
      function highlightSiblings()  {
          clearAll();  
          $('h2').siblings().css("background","yellow");
      }
      function highlightNext()  {
          clearAll();    
          $('h2').next().css("background","yellow");
      }
      function highlightNextAll()  {
          clearAll();    
          $('h2').nextAll().css("background","yellow");
      }
      function highlightNextUntil()  {
          clearAll();    
          $('h2').nextUntil('h4.blue').css("background","yellow");
      }
      function highlightPrev()  {
          clearAll();    
          $('h2').prev().css("background","yellow");
      }
      function highlightPrevAll()  {
          clearAll();    
          $('h2').prevAll().css("background","yellow");
      }
      function highlightPrevUntil()  {
          clearAll();    
          $('h2').prevUntil('h1').css("background","yellow");
      }                                              
   </script>
   
</head>
<body>

   <h3>jQuery Traversing - siblings</h3>
 
   <input type="button" onclick="highlightSiblings();" value="siblings()"/>
   <input type="button" onclick="highlightNext();" value="next()"/>
   <input type="button" onclick="highlightPrev();" value="prev()"/>
   
   <input type="button" onclick="highlightNextAll();" value="nextAll()"/>
   <input type="button" onclick="highlightPrevAll();" value="prevAll()"/>
   
   <input type="button" onclick="highlightNextUntil();" value="nextUntil()"/>
   <input type="button" onclick="highlightPrevUntil();" value="prevUntil()"/>
   
   
   <a href="">Reset</a>
       
 
       
    <div>div element
       <h1 class='blue'>h1 element (Until)</h1>  
       <div>div element</div>
       <div>div element</div>
       <h2>h2 element (current)</h2>
       <p>p element</p>
       <div>div element
           <br>
           <p style="background:white;">p element</p>
       </div>
       <h1>h1 element</h1>
       <h4>h4 element</h4>
       <h4 class='blue'>h4 element class='blue'  (Until)</h4>
       <div>div element</div>  
    </div>
   

   
</body>
</html>
Running the example:

6- jQuery Event

The events is supported in DOM model:
Event Types Event Description
MOUSE EVENT click Occurs when a mouse click.
dblclick Occurs when a mouse double-click.
mouseenter Occurs when mouse enters in an element region.
mouseleave Occurs when mouse leaves an element region.
 
KEYBOARD EVENT keypress Occurs when key is pressed and released.
keydown Occurs when key is pressed.
keyup Occurs when key is released.
 
FORM EVENT submit Occurs when form is submitted.
change Occurs when the element changes.
focus Occurs when the element gets focus.
blur Occurs when the element loses focus.
 
DOCUMENT/WINDOW EVENT load Occurs when document is loaded.
resize Occurs when window is resized.
scroll Occurs when window is scrolled.
unload Occurs when documents is unloaded.
error Occurs when there is an error in loading or unloading etc.

6.1- Common way to handing event

You need to attach (bind) a function with a certain event of element. When events occur that function will be executed. Examples attaching a function to the event click on all the elements <h3>.
// At the moment the page is ready
$(document).ready(function() {

   // Attach an event handler to the "click" event of h3 elements.
   $("h3").click(function() {
       // Use $(this) to refer element fire this event. (h3)
       $(this).css("background:#ccc");
   });

   // Attach an event handler to the "dblclick" event of h4 elements.
   $("h4").dblclick(function(){
       // Use $(this) to refer element fire this event. (h4)
       $(this).css("background:yellow");
   });
 
});
  • event_helloworld.html
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery Event - Hello World example</title>


    <style>
       h3 {border: 1px solid blue; padding: 5px; width: 200px;}
       h4 {border: 1px solid red; padding: 5px; width: 200px;}
    </style>
        
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
 
    
    <script>
    
 
        // At the moment the page is ready
        $(document).ready(function() {

      
           // Attach an event handler to the "click" event of h3 elements.
           $("h3").click(function(){
         
               // Use $(this) to refer element fire this event. (h3)
               $(this).css("background","#ccc");
           });

      
           // Attach an event handler to the "dblclick" event of h4 elements.
           $("h4").dblclick(function() {
      
               // Use $(this) to refer element fire this event. (h4)
               $(this).css("background","yellow");
           });
        
        });
        
    </script>
    

</head>
<body>
    <h2>jQuery Event - Hello World example</h2>
    <a href="">Reset</a>
    
    <h3>H3 - Click me!</h3>
    <h3>H3 - Click me!</h3>
    
    <h4>H4 - Double Click me!</h4>
    
</body>
</html>
Running the example:

6.2- Using bind()/unbind()

You can use the bind() to attach a handler to an event for elements.
Syntax:
selector.bind( eventType[, eventData], handler)
 
Arguments:
  • eventType − A string containing a JavaScript event type, such as click or submit. See the list of events in the table above.
  • eventData − This is optional parameter is a map of data that will be passed to the event handler.
  • handler − A function to execute each time the event is triggered.

 
Example:
$(document).ready(function() {

    $('div').bind('click', function( event ){
        alert('Hi there!');
    });

});
You can use unbind() to remove the event handler.
Syntax:
selector.unbind(eventType, handler)

// or

selector.unbind(eventType)
Parameters:
  • eventType − A string containing a JavaScript event type, such as click or submit.  
  • handler − If provided, identifies the specific listener that's to be removed.
  • event_bind_unbind.html
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery Event - bind()/unbind() example</title>


    <style>
       h3 {border: 1px solid blue; padding: 5px; width: 300px;}
       h4 {border: 1px solid red; padding: 5px; width: 300px;}
       
       p {border: 1px solid green; padding: 5px; width: 300px;}
    </style>
        
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
 
    
    <script>
    
    
        // At the moment the page is ready
        $(document).ready(function() {
             
   
           // Bind an event handler to the "click" event of h3 elements.
           $("h3").bind('click', function() {
               $(this).css("background","#ccc");
           });

    
           // Bind an event handler to the "dblclick" event of h4 elements.
           $("h4").bind('dblclick', function(){
               $(this).css("background","yellow");
           });
           
           $("p").bind('click', function()  {
       
               // Remove the event handler click on h3.
               $("h3").unbind("click");
               $("h3").text("click handler removed!");
               $("h3").css("background", "white");               
           });        
        });
        
    </script>
    

</head>
<body>
    <h2>jQuery Event - bind()/unbind() example</h2>
    <a href="">Reset</a>
    
    <h3>H3 - Click me!</h3>
    <h3>H3 - Click me!</h3>
    
    <h4>H4 - Double Click me!</h4>
    
    <p>Click to remove click handler in h3</hp>
</body>
</html>
Running the example

6.3- Event Attribute

S.NO. Property Description
1 altKey Set to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards.
2 ctrlKey Set to true if the Ctrl key was pressed when the event was triggered, false if not.
3 data The value, if any, passed as the second parameter to the bind() command when the handler was established.
4 keyCode For keyup and keydown events, this returns the key that was pressed.
5 metaKey Set to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs.
6 pageX For mouse events, specifies the horizontal coordinate of the event relative from the page origin.
7 pageY For mouse events, specifies the vertical coordinate of the event relative from the page origin.
8 relatedTarget For some mouse events, identifies the element that the cursor left or entered when the event was triggered.
9 screenX For mouse events, specifies the horizontal coordinate of the event relative from the screen origin.
10 screenY For mouse events, specifies the vertical coordinate of the event relative from the screen origin.
11 shiftKey Set to true if the Shift key was pressed when the event was triggered, false if not.
12 target Identifies the element for which the event was triggered.
13 timeStamp The timestamp (in milliseconds) when the event was created.
14 type For all events, specifies the type of event that was triggered (for example, click).
15 which For keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right).
See example:
  • event_attribute.html
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery Event attribute example</title>


    <style>
       div {margin : 10px; width: 250px; height: 150px; float: left; }
    </style>
        
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
 
    
    <script>
    
        $(document).ready(function() {
         
           $("div").click(function(event) {  
               var s="Type  = "+ event.type+ "<br>"
                    +"pageX = "+ event.pageX+"<br>"
                    +"pageY = "+ event.pageY+"<br>"
                    +"screenX = "+ event.screenX+"<br>"
                    +"screenY = "+ event.screenY+"<br>"
                    +"which = "+ event.which+"<br>"
                    +"target = "+ event.target.innerHTML+"<br>"
                    ;
                    
               $('div#log').html(s);
           });
 
        });
        
    </script>
    

</head>
<body>
    <h2>jQuery Event attribute example</h2>
    
    
    <div style="background:blue;">
       DIV 1
    </div>
    
    <div style="background:red;">
       DIV 2
    </div>
    
    <hr style="clear:both;"/>
    
    <div id="log" style="border:1px solid #ccc;padding:10px;width:550px;">
   
    
    </div>
</body>
</html>
Running example:

6.4- Event methods

No. Method Description
1 preventDefault() Prevents the browser from executing the default action.
2 isDefaultPrevented() Returns whether event.preventDefault() was ever called on this event object.
3 stopPropagation() Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
4 isPropagationStopped() Returns whether event.stopPropagation() was ever called on this event object.
5 stopImmediatePropagation() Stops the rest of the handlers from being executed.
6 isImmediatePropagationStopped() Returns whether event.stopImmediatePropagation() was ever called on this event object.
Ví dụ khi bạn nhấn chuột phải vào trang web, mặc định một cửa sổ popup hiển thị lên. Bạn có thể sử dụng preventDefault() để ngăn chặn hành động mặc định này của trình duyệt.
// Hủy hiển thị của sổ contextmenu khi nhấn phải chuột vào thẻ div có id= div2
$("div").bind('contextmenu', function(event) {
   if( $(this).attr('id') == "div2")  {
      event.preventDefault();
   }
});

// Huỷ hành động mặc định khi nhấn vào thẻ <a>
$("a").click(function(event)  {
  event.preventDefault();
  alert("a element not working!!");
});
See full example:
  • event_preventDefault.html
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery Event preventDefault()</title>


    <style>
       div {margin : 10px; padding:5px; width: 250px; height: 150px; float: left; }
    </style>
        
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
 
    
    <script>
    
        $(document).ready(function() {
         
           $("div").bind('contextmenu', function(event) {
               if( $(this).attr('id') == "div2")  {
                   event.preventDefault();
               }
           });
           
           $("a").click(function(event)  {
               event.preventDefault();
               alert("a element not working!!");
           });
            
        });
        
    </script>
    

</head>
<body>
    <h2>jQuery Event preventDefault() example: Disable contextmenu on right click</h2>
    
    <a href="http://jquery.com">Go to jQuery.com (Not working)</a>
    <br>
    
    <div style="background:blue;" id="div1">
       Right-click to show context menu
    </div>
    
    <div style="background:red;" id="div2">
        Disable context menu
    </div>
    
    
    
</body>
</html>
Running example:
  • event_stopPropagation.html
<html>
<head>
    <meta charset="utf-8">
    <title>jQuery Event stopPropagation()</title>


    <style>
       div {margin : 20px; padding:5px; float: left; }
       .outerDiv {background: red; width: 250px; height: 150px; }
       .innerDiv {background: yellow; width: 250px; height: 100px; }
    </style>
        
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>
 
    
    <script>
    
        $(document).ready(function() {
         
           $("div").click( function(event) {
               if( $(this).attr('id') == "stopDiv")  {
                   event.stopPropagation();
               }
               alert("click "+ $(this).html());
           });
            
        });
        
    </script>
    

</head>
<body>
    <h2>jQuery Event stopPropagation() example</h2>
    
   
    
    <div class="outerDiv">
       Outer Div
       <div class="innerDiv">
          Inner Div
       </div>
    </div>
    
    <div class="outerDiv">
        Outer Div
        <div class="innerDiv" id="stopDiv">
          Inner Div (stopPropagation)
       </div>       
    </div>
    
    
</body>
</html>
Running example: