Gajendra Yaduwanshi

jQuery Event Methods

What is jQuery Event Methods?

In most web applications, the user does some action to perform an operation. For example, the user clicks on the save button to save the edited data on a web page. Here, clicking on the button is a user’s action, which triggers click event and clicks event handler (function) saves data.

jQuery events

All the different visitors’ actions that a web page can respond to are called events.

An event represents the precise moment when something happens.

Examples:

  • moving a mouse over an element
  • selecting a radio button
  • clicking on an element

The term “fires/fired” is often used with events. Example: “The keypress event is fired, the moment you press a key”.

Here are some common DOM events:

CategoryjQuery MethodDOM Event
Form eventsbluronblur
 changeonchange
 focusonfocus
 focusinonfocusin
 selectonselect
 submitonsubmit
Keyboard eventskeydownonkeydown
 keypressonkeypress
 keyuponkeyup
 focusout 
Mouse eventsclickonclick
 dblclickondblclick
 focusout 
 hover 
 mousedownonmousedown
 mouseenteronmouseenter
 mouseleaveonmouseleave
 mousemoveonmousemove
 mouseoutonmouseout
 mouseoveronmouseover
 mouseuponmouseup
 Toggle 
Browser eventsErroronerror()
 Resizeonresize
 Scrollonscroll
Document loadingLoadonload
 Ready 
 Unloadonunload

Event Handling

To handle DOM events using jQuery methods, first get the reference of DOM element(s) using jQuery selector and invoke appropriate jQuery event method.

The following example shows how to handle button click event.

Example:

$(‘#saveBtn’).click(function () {

 alert(‘Save button clicked’); 

}); 

<input type=”button” value=”Save” id=”saveBtn” />

In the above example, we first use id selector to get a reference of ‘Save’ button and then call click method. We have specified handler function as a callback function, which will be called whenever click event of Save button is triggered.

Event Object

jQuery passes an event object to every event handler function. The event object includes important properties and methods for cross-browser consistency e.g. target, pageX, pageY, relatedTarget etc.

Example:

$(‘#saveBtn’).click(function (eventObj) {

 alert(‘X =’ + eventObj.pageX + ‘, Y =’ + eventObj.pageY);

 }); 

<input type=”button” value=”Save” id=”saveBtn” />

this Keyword in Event Handler

this keyword in an event handler represents a DOM element which raised an event.

Example:

$(‘:button’).click(function (eventObj) { 

  alert(this.value + ‘ ‘ + this.type + ‘ clicked’); 

}); 

<input type=”button” value=”Save” id=”saveBtn” /> 

<input type=”button” value=”Delete” id=”delBtn” /> 

<input type=”button” value=”Clear” id=”clearBtn” />

Hover Events

jQuery provides various methods for mouse hover events e.g. mouseenter, mouseleave, mousemove, mouseover, mouseout and mouseup.

Example:

$(‘#myDiv’).mouseenter(function(data)

{

 $(this).css(‘background-color’,’green’); 

}); 

 $(‘#myDiv’).mouseleave(function(data)

 $(this).css(‘background-color’,’red’); 

}); 

<div id=”myDiv” style=”width:100px;height:100px”></div>

You can use hover() method instead of handling mouseenter and mouseleave events separately.

Example:

$(‘#myDiv’).hover(function () { 

$(this).css(‘background-color’,’green’); 

}, 

function () { 

$(this).css(‘background-color’,’red’); 

}); 

<div id=”myDiv” style=”width:100px;height:100px”> </div>

Event Binding using on()

jQuery allows you to attach an event handler for one or more events to the selected elements using on method.

Internally all of the shorthand methods uses on() method. The on() method gives you more flexibility in event binding.

Syntax:

on(types, selector, data, fn )

  • Types = One or more space-separated event types and optional namespaces
  • Selector = selector string
  • Data = data to be passed to the handler in event.data when an event is triggered.
  • Fn = A function to execute when the event is triggered.
Example:

$(‘#saveBtn’).on(‘click’,function () { 

 alert(‘Save Button clicked’); 

});

 <input type=”button” value=”Save” id=”saveBtn” />

You can use selector to filter the descendants of the selected elements that trigger the event.

Example:

$(‘#myDiv’).on(‘click’,’:button’, function () {

 alert(‘Button clicked’); 

}); 

<div id=”myDiv” > 

   <input type=”button” value=”Save” id=”saveBtn” /> 

   <input type=”button” value=”Add” id=”addBtn” /> 

</div> 

<input type=”button” value=”Delete” id=”delBtn” />

In the above example, we specify ‘:button’ selector. So click event triggered by buttons in <div> tag whose id is myDiv, will only be handled.

Binding Multiple Events

You can also specify multiple event types separated by space.

Example:

$( ‘myDiv’ ).on(‘mouseenter mouseleave’, function() { 

$(this).text(‘The mouse entered or left from the div’ ); 

}); 

<div id=”myDiv” style=”width:100px;height:100px”> </div>

Specify Named Function as Event Handler

You can create separate functions and specify that as a handler. This is useful if you want to use the same handler for different events or events on different elements.

Example:

var mouseHandler = function() {

 alert( “The mouse entered” ); 

}; 

$(‘#myDiv’).on(‘mouseenter’, mouseHandler); 

<div id=”myDiv” style=”width:100px;height:100px”> </div>

jQuery on() method is replacement of live() and delegate() method.

Event Bubbling

The following example demonstrates event bubbling in jQuery.

Example:

$(‘div’).click(function (event) {

  alert( event.target.tagName + ‘ clicked’);

 }); 

<div> <p> <span>This is span.</span> </p> </div>

As you can see in the above example, we have handled click event of <div> element in jQuery. So if you click on div, it will display alert message ‘DIV clicked’. However, if you click on span, still it will popup alert message SPAN clicked even though we have not handled click event of <span>. This is called event bubbling. Event bubbles up to the document level in DOM hierarchy till it finds it.

jQuery Event Bubbling
Share