Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now

jQuery Events

13 Feb 2024
Intermediate
6.15K Views
13 min read
Learn with an interactive course and practical hands-on labs

Free ReactJS Foundation Course: React JS Online Course Free

When a user clicks on the button, selecting the item from the dropdown or mouse over the HTML elements, all these kinds of event handling gets simplified by using the jQuery events shortcut functions, in this article, you will learn about following features in jQuery Event handling

  • jQuery Event Model Benefits

  • Handling Events

  • Binding to Events

  • live(), delegate(), on ()

  • Handling Hover Events

jQuery Event Model Benefits

Let's start with a simple question.

How you will write a code to handle the button click event in JavaScript?

Answer: it will depend on the browser. In Javascript we use addEventListener to attach the event for the element, as written below

myButton.addEventListener('click', function(){ })

In IE 8 and earlier

myButton.attachEvent('onclick',function(){}),

jQuery Event Modal will simplify it by wrapping up both the functionality. It will take of everything based on the browser jQuery provides a cross-browser event modal it is simple to use with compact and simplified syntax

Read More - jQuery Interview Questions for Freshers

Handling Events

List of jQuery Events Shortcut functions

  • click()

  • change()

  • blur()

  • focus()

  • dbclick()

  • mousedown()

  • mouseup()

  • mouseover()

  • keydown()

  • keypress()

  • keyup()

and many more

Event
Example
Description
click()
$(selector).click(function(){})
Click Event fire when the user clicks on the elements
change()
$(selector). change (function(){})
Change Event fire when there is any change in input elements
focus()
$(selector). change (function(){})
Focus Event fire when the element is focused
blur()
$(selector). change (function(){ })
Blur Event fire when the element is focused out
dbclick()
$(selector). change (function(){ })
Double Click Event fire when the element is double clicked
mouseenter()
$(selector). mouseenter (function(){})
Mouse enter event fire when the mouse enters into the element
mouseleave()
$(selector). mouseleave (function(){ })
Mouse leave event fire when the mouse leaves the element
mouseup()
$(selector). mouseup (function(){})
Mouse up event fire when the mouse click happens on the element
on()
$(selector). on('click',function(){ })
On function is used to binding the event handler to the element
$(selector).on('mouseenter mouseleave mouseup',function(e) { } });
Binding multiple events using on()
off()
$(selector). off()
Unbound the event attached to the element
$(selector). off('click')
Unbound specific element attached to the element
hover()
$(selector). hover(function(){ })
Hover event is combination of mouseenter and mouseleave event.
click()

.click(handler(eventObject)) is used to track a click event on an element. Basically the click event is used for the button

$(selector).click(function(){
 //action to perform
})
Example:

HTML

 <button id="btnSubmit">Click Me</button>
 

JavaScript

 $("#btnSubmit").click(function() {
 
 alert("Hi I'm jQuery Click Event"); 
})
 

Alert Box in Browser

The above example shows how to work with click event. First, we need to choose a proper selector, in this case, I need to track the click event of the button, so the best way is to use the ID selector of a button followed with events and call back function which has an alert as its definition. We can re-write the above code by breaking as a function which is easier to maintain

JavaScript

 $(document).ready(function() {
 ClickEventDemo();
 });
 
 function ClickEventDemo() {
 $("#btnSubmit").click(function() {
 
 alert("Hi I'm jQuery Click Event");
 });
 }
 
Change():

Major use case of the change event is to capture the change in dropwdown list item selection, not only the dropdown list we can apply to other input controls like textbox, textarea and many more

Capturing the change in dropdown list

HTML

 <select id="selectCountry" name="country-select">
 <option value="India">India</option>
 <option value="China">China</option>
 <option value="Singapore">Singapore</option>
 </select>
 

JavaScript

 $('#selectCountry').change(function() {
 alert($(this).val()); 
 });
 

($(this).val()) will return the current object value, In this case it is selected country Name

Result in Browser

Source codehttps://jsfiddle.net/fozkbLt4/

Change event for TextBox

HTML

 <input id="txtEmail" type="text" placeholder="Enter Email" name="email" required>
 

CSS

 .improvise {
 background-color: aqua !important;
 }
 </style>
 

JavaScript

 $('#txtEmail').change(function() {
 $(this).addClass('improvise');
 
 });
 

Result in Browser

Source code https://jsfiddle.net/fozkbLt4/

focus();

This event fire when the element is focused

JavaScript Snippet

 <input id="txtEmail" type="text" placeholder="Enter Email" name="email" required>
 $('#txtEmail').focus(function() {
 alert("I'm Focus Event");
 });
 

Alert Box in Browser

blur():

This event fire when the element is focused out

JavaScript Snippet

 <input id="txtEmail" type="text" placeholder="Enter Email" name="email" required="">
 $('#txtEmail').blur(function () {
 alert("I'm Blur Event");
 });
 

Alert Box in Browser

dbclick()

This event fire when the element is double clicked

JavaScript Snippet

 $('#txtEmail').dblclick(function () {
 alert("I'm Double Click Event");
 });
 

Alert Box in Browser

Mouse Events

Mouse Enter

This event get fire when the mouse enter into the object.

JavaScript Snippet

 $('.container').mouseenter(function() {
 $(this).toggleClass('improvise');
 })
 

From the above code it is obvious when the mousenter into the object whose class name is 'container' jQuery automatically toggle its class based on the definition.

Source code https://jsfiddle.net/fozkbLt4/

Chaining the Events

We can chain the events as written below

JavaScript Snippet

 $('.container').mouseenter(function() {
 $(this).toggleClass('improvise');
 }).mouseleave(function() {
 $(this).toggleClass('improvise');
 });
 

From the above code it is obvious when the mousenter and mouseleave the object whose class name is 'container' jQuery automatically toggle its class based on the definition.

Result in Browser

Mouse leave

Passing actual event object

Whatever function we have discussed above and going to be discussed will contains an event object. The below written code will explain you how to get the event object.

JavaScript Snippet

 $('.container').mouseenter(function() {
 $(this).toggleClass('improvise');
 }).mouseleave(function() {
 $(this).toggleClass('improvise');
 }).mouseup(function(event) {
 $(this).text('X:' + event.pageX + 'Y:' + event.pageY);
 });
 

MouseUp event will fire when you click on the object, In this case the mouseup event will get called when the user click on the element which contains a class name as 'conainer' and change the text based on the information available in event object for event.pageX and event.pageY.

Result in Browser

event.target will gives you actual object

JavaScript Snippet

 mouseup(function(event) {
 alert(event.target) 
 });
 

Alert Box in Browser

Binding to Events

on()

Binding to events can be done in jQuery using the "on" function. The "on" function is the core event function of jQuery which basically used to attach a handler to an event for the selected element.

 $("#myElement").on("click",function(){
 //perform a action
 })
 

Note: on() added in jQuery 1.7 and above

HTML

 <button id="btnSubmit" class="registerbtn">Register</button>
 

JavaScript

 $("#btnSubmit").on('click',function() {
 alert("Hi I'm jQuery on function with Click Event");
 });
 

The above code will tells you how to bind the events using the on().

Alert Box in Browser

Note: Since on() is the core event function in jQuery, it is always recommended to use on() instead of using other event shortcut function

off()

off Event is used to remove a handler previously bound to an element

example
 $("#myElement").on("click",function(){
 //perform a action
 })

This can be unbound using $('# myElement').off()

 $("#btnSubmit").off() 
 

This will off the events attached to "btnSubmit" element

$('# myElement').off() will unbound all the event handler attached to myElement. To be specific to the event we can re-write it as

 $('# myElement').off('click') ; 
 

The above statement will remove only click event handler from myElement

Binding Multiple Events

on() and off() allow multiple events to be bound and unbound to an element respectively. Events name to be bind/unbind are separated with the space

 $("#myElement").on('mouseenter mouseleave',function(){
 //perform an action
 })
 

JavaScript Snippet

 $('.container').on('mouseenter mouseleave mouseup',
 function(e) {
 $(this).toggleClass('improvise');
 if (e.type === "mouseup") {
 $(this).text('X:' + event.pageX + 'Y:' + event.pageY);
 alert(event.target);
 }
 });
 

Above code will tells you how to bind multiple events using on(). e.type, will gives you what type of event.

 $('.container').off("mouseup"), 
 

this statement will unbound particular mouseup event from the multiple event binding.

live(), delegate() and on()

  • delegate() and on() allow new DOM element to automatically be attached to an event handler

  • Allow children to be added to a container without explicitly attaching an event handler to each child

  • live() delegate() and on() attach event handler at higher level, when child is clicked or any event in performed it will automatically bubbled up

Consider if you have 1000 rows in a table and you need to attach the event for all the rows, now Instead of adding event handler for each element we can attach the event handler at higher parent level which will reflect to its children. So when user clicks on child element which doesn't have event handler, will bubble up and the event get fired based on the event attached with parent. Note : As of jQuery 1.7+ live() is depreciated , we can use delegate() with jQuery 1.4.3+ or on() with jQuery 1.7+

delegate()

unlike live() the delagates() works even when new objects are added in the DOM

HTML

 <table>
 <tr class="myclass"></tr>
 <tr class="myclass"></tr>
 <tr class="myclass"></tr>
 …………
 </table> 
 $("table").delegate('.myclass','click',some function);
 

$("table") is with any child(tr) of table is clicked the call back function will get fired We can stop delegate event handling using undelegate() The on() function is a new replacement for the following functions

  • bind()

  • delegate()

  • live()

Example

JavaScript Snippet

 $('table').on('click','tr',function(e)
 {
 alert("Click event attached to parent level bubbled up while clicking on child <tr>")
 })
 

From the above code is the clear evidence you can replace the delegate() with on()

Result in Browser

https://jsfiddle.net/fozkbLt4/ Mapping a different call back function using on()

JavaScript Snippet

 $("table tr").on({
 mouseenter: function() {
 $(this).toggleClass('improvise');
 },
 mouseleave: function() {
 $(this).toggleClass('improvise');
 }
 });
 

From the above code you can observe mouseenter and mouseleave event call back return in a single block using on().

Result in Browser

MouseEnter

Mouse Leave

Handling Hover Events

Hover events can be handled using hover()

$(selector).hover(handlerIn,handlerOut) handlerIn is equivalent to mouseenter and handlerOut is equivalent to mouseleave

Example

JavaScript Snippet

 $('table tr').hover(
 function(){
 $(this).css('background-color', 'aqua'); //similar to mouseenter
 },
 function(){
 $(this).css('background-color', '#FFFFFF');//similar to mouseleave
 }
 
 );
 

The above code still can be improvised

JavaScript Snippet

 $('table tr').hover(function() {
 $(this).toggleClass('improvise');
 });
 

This code fires same event handler for mouseenter and mouseleave events, just it provides the flexibility of writing the function.

Result in Browser

Summary

We have seen how jQuery simplifies handling the cross-browser event attachment, and the use of build in shortcut functions, finally we have seen the benefit of event binding using the on (). Complete Source code available in https://jsfiddle.net/fozkbLt4/

Share Article
About Author
Gowtham K (Microsoft MVP and Sr. Software Engineer)

He is having around 5 years of working experience in various technologies like C#, ASP.NET, MVC, Azure, JavaScript, jQuery, CSS and HTML. He loves to work on various web technologies, his passion is to learn, experiment, and share knowledge.
Accept cookies & close this