jQuery Events

You will learn about jQuery events in this section.

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

jQuery events
Event

jQuery Event Methods

The jQuery library provides methods to handle DOM events. Most jQuery methods correspond to native DOM events.

The following table lists all jQuery methods and corresponding DOM events.

Category jQuery Method DOM Event
Form events blur onblur
change onchange
focus onfocus
focusin onfocusin
select onselect
submit onsubmit
Keyboard events keydown onkeydown
keypress onkeypress
keyup onkeyup
focusout
Mouse events click onclick
dblclick ondblclick
focusout
hover
mousedown onmousedown
mouseenter onmouseenter
mouseleave onmouseleave
mousemove onmousemove
mouseout onmouseout
mouseover onmouseover
mouseup onmouseup
Toggle
Browser events Error onerror()
Resize onresize
Scroll onscroll
Document loading Load onload
Ready
Unload onunload

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:Handle Button Click Event
$('#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: jQuery Event Object
$('#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: this in Event Handler
$(':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: Hover Events
$('#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: hover() Method
$('#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: Event Binding using on
$('#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: Event Binding using on
$('#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: Multiple Events Binding
$( '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:Binding Named Function to Event
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:Event Bubbling
$('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.

The following figure illustrates event bubbling.

jQuery Event Bubbling
jQuery Event Bubbling

Visit event methods reference to know about all the event methods in jQuery.

Points to Remember :
  1. The jQuery event methods allow you to attach event handler or fire native DOM events.
  2. Use the selector to get the reference of an element(s) and then call jQuery event methods to fire it or attach an event handler.
  3. Important DOM manipulation methods: click(), dblClick(), change(), submit(), keyup(), keydown(), mouseenter(), mouseleave(), hover() etc.
Want to check how much you know jQuery?