jQuery Events

jQuery is all about making the webpage more interactive. In this article, we will learn about the various jQuery events (actions) which help making a page more interactive. If you don't know what jQuery is and how to use it, please read jQuery Library and jQuery Syntax first.

Let us learn by looking at a simple example:
  1. <html>  
  2. <head>  
  3.    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>  

  4.    <
    style>  
  5.       #div1{  
  6.          background-color:blue;  
  7.          color:white;  
  8.          height: 5%;  
  9.          width: 50%;  
  10.          text-align:center;  
  11.       }  
  12.    </style>  
  13.   
  14. </head>  

  15. <body>  
  16.    
  17.    <div id="div1">  
  18.       <b>Click me to trigger jQuery Event.<b>  
  19.    </div>  
  20.   
  21.    <script type="text/javascript">  
  22.   
  23.       $(document).ready(function() {  
  24.          $("#div1").on("click",function(){  
  25.             alert("Division is Clicked");  
  26.          });  
  27.       });  
  28.   
  29.    </script>  
  30.   
  31. </body>  
  32. </html>  
Output

Output
When you click anywhere in the division, you will get an alert.

Output
So, How does the alert gets called?

As you can see, inside the document ready function, we are selecting division using it's id "div1". Then, comes the action. Here, the action is "on()" method. The on() method attaches one or more event handlers for the selected element. In our example, the selected element is div1, and we add an event handler "click" to it. Then, we have a function which has alert message. This is similar to onclick event of JavaScript.

So, we bound the division with an event handler. Whenever the user clicks anywhere in the division, the alert message will be displayed.

In the similar way, we can use various events in jQuery. Let's have a quick overview of few of them.

click()
This function will be executed whenever the user clicks on the selector element.
 
Example:
  1. $("p").click(function(){  
  2.    alert("Paragraph was clicked");  
  3. });   
focus()
This function will be executed whenever the field will get focused.

Example: 
  1. $("input").focus(function(){  
  2. $(this).css("color""red");  
  3. });  
hover()
This function will be executed whenever the mouse enters the element. 
 
Example:
  1. $("#div1").hover(function(){  
  2.    $(this).css("background-color","red");   
  3. });  
blur()
This function will be executed whenever the field loses the focus. 
 
Example:
  1. $("input").blur(function(){  
  2.     $(this).css("color""black");  
  3. });  
Try out these events and see the output for each of them.