Introduction
Any action that happens on a webpage can be considered as an event. For example, mouse click, key press, button click, radio button select etc are events. An event is said to be fired or triggered at the exact moment something happens. For example, the button click event is fired the moment you click the button.
jQuery offers equivalent methods for every DOM event and these methods are used to define behaviours to take effect when the specific action occurs. Some of the popular jQuery methods are click, dblclick, load, keypress, keyup, mouseenter, focus, blur, scroll etc. jQuery event model allows us to attach an event handler using the methods on selected HTML elements. For example, you can attach the click event on the button as $("button").click().
Once the event is attached, you should define what need to happen (behaviour to take effect) when the event is fired. We need to pass a function to the event in order to define it. Inside the function, we have to write the code.
$("button").click(function(){ alert("You clicked the button"); });
Different Events
jQuery offers a number of methods to attach events to the selected HTML elements. When you try each of the sample code given below, make sure that you add reference to the latest version of jQuery file correctly.
1. click()
The click method is executed when the user clicks on the selected HTML element.
Try this yourself:
<html> <head> <title>Sample Code</title> <style> </style> <script src="jquery.js"></script> <script> $(document).ready(function() { $("button").click(function(){ alert("You clicked me!!!"); }); }); </script> </head> <body> <button>Click Me!!!</button><br /> </body> </html>
2. dblclick()
The dblclick method is executed when the user double clicks on the selected HTML element.
Try this yourself:
<html> <head> <title>Sample Code</title> <style> </style> <script src="jquery.js"></script> <script> $(document).ready(function() { $("span").dblclick(function(){ $("span").css({"color":"red"}); }); }); </script> </head> <body> <span>Double-Click Me to Change My Color!!!</span> </body> </html>
Here is the output once you double click the element:
3. hover()
The hover method is triggered when both mouseenter and mouseleave events happen. So, you can specify two functions to run when the mouse pointer enters the element and also leaves the element. If you specify only one function, then it will be executed for both mouseenter and mouseleave events.
Try this yourself:
<html> <head> <title>Sample Code</title> <style> </style> <script src="jquery.js"></script> <script> $(document).ready(function() { $("span").hover(function(){ $("span").text("Mouse In"); }, function(){ $("span").text("Mouse Out"); }); $("p").hover(function(){ $("p").css("background-color","red"); }); }); </script> </head> <body> <span style="font-size:40px;color:red;">Hover over Here!!!</span> <p style="font-size:20px;color:purple;">Mouse over here!!!</p> </body> </html>
Here, we have specified two separate functions for the hover of span element so that the message "Mouse In" is displayed when the mouse enters the span and the message "Mouse Out" is displayed when the mouse leaves the span. In case of the p element's hover method, we specified only one function so that it is executed for both mouseenter and mouseleave events.
4. focus()
The focus method is triggered when the element gets focus.
Try this yourself:
<html> <head> <title>Sample Code</title> <style> </style> <script src="jquery.js"></script> <script> $(document).ready(function() { $("#password").focus(function(){ if($("#uname").val() == "") alert("Enter your user name."); else alert("Welcome " + $("#uname").val() + ". Enter your password."); }); }); </script> </head> <body> User Name: <input type="text" id="uname" /><br /> Password: <input type="text" id="password"/> </body> </html>
Here, we attach the focus method to the password textbox. Then, we display one message if the user tries to enter the password without entering user name and another message if the user tries to enter the password after entering the user name.
5. scroll()
The scroll method is triggered when the user scrolls in an element.
Try this yourself:
<html> <head> <title>Sample Code</title> <style> </style> <script src="jquery.js"></script> <script> x=0; $(document).ready(function() { $("div").scroll(function(){ $("span").text(x+=1); }); }); </script> </head> <body> <div style="border:2px solid black;width:100px;height:100px;overflow:scroll;"> This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample. This is a sample.</div> <p>No: of scrolls:<span>0</span></p> </body> </html>
Here, we make a <div> element scrollable and then attach scroll method to it. Every time, the user scrolls in the element, we increase the number of scrolls value by 1. If you scrolls in the <div> element a number of times, your output will look like this:
6. keydown() and keyup()
The keydown method is triggered when a key is pressed down and the keyup method is triggered when the pressed key is released.
Try this yourself:
<html> <head> <title>Sample Code</title> <style> </style> <script src="jquery.js"></script> <script> x=0; $(document).ready(function() { $("#txtInput").keydown(function(){ $("#txtInput").css("background-color","red"); }); $("#txtInput").keyup(function(){ $("#txtInput").css("background-color","yellow"); }); }); </script> </head> <body> Enter Input:<input id="txtInput" /> </body> </html>
The output when you press down a key will be this (the textbox in red color):
The output when you release a key will be this (the textbox in yellow color):
7. on() and off()
The on method can be used to attach one or more event handlers to the selected elements. You can share the same handling function for multiple events by just separating the events using space. You can also bind multiple events with different handling function. In that case, you need to pass them as key/value pairs where the key being the event and the handling function being the value.
You can use the off method to remove an event handler attached using the on method.
Try this yourself:
<!DOCTYPE html> <head> <title>Sample Code</title> <style> </style> <script src="jquery.js"></script> <script> $(document).ready(function() { //multiple events sharing the same handling function $("div").on( "click scroll", function() { alert("Clicked or Scrolled"); }); //multiple events with different handling functions // event:handling function $("div").on({ "mouseenter":function(){$("div").css("font-size","50px");}, "mouseleave":function(){$("div").css("font-size","20px");} }); //Off the handler $("button").click(function(){ $("div").off("scroll"); }); }); </script> </head> <body> <div style="border:1px solid black;height:100px;width:200px;overflow:auto;">Enter in or Move out to Change the Style!!!Click or Scroll to See the Message!!!</div> <br /><button>Remove the Scroll Handler</button> </body> </html>
When the user clicks or scrolls the element, a message like this appears:
When the mouse enters the element, the size of the content is increased and when the mouse leaves the element, the size of the content is decreased. After clicking the button, if you scroll the element, nothing will happen as we remove the scroll event handler on the click of the button.
Event Chaining
jQuery allows you to chain together different methods. You do not have to repeatedly attach different event handlers for the same element. In other words, you can run multiple methods on the same element using method chaining. To accomplish this, you just need to append the method to the previous method.
Try this yourself:
<!DOCTYPE html> <head> <title>Sample Code</title> <style> </style> <script src="jquery.js"></script> <script> $(document).ready(function() { $("button").click(function(){ $("div").css("color", "red").css("font-size","50px").fadeToggle("slow"); }); }); </script> </head> <body> <div>This is the Content!!!</div> <button>Click</button> </body> </html>
When the button is clicked, the content will become red first, then its size will be increased and finally it will be faded out. Though the methods occur in the order from left to right, we are not able to see it clearly as they happen so fast. If you again click the button, you will get this output as the content will be faded in.
Summary
We have seen how to attach different methods to the selected element(s). We have also seen how to chain methods easily. jQuery offers many more methods to handle all different types of events. You can find the full list in the official website of jQuery.