Comprehensive Look at Events in jQuery
Almost all user interactions within a webpage can be captured in jQuery as events. Events are important in the sense that they allow you to respond appropriately based on a user’s actions. For instance, you can write code that changes the background color of a webpage based on button click or scrolling events.
More from this author
jQuery has many shortcut methods, like contextmenu()
, hover()
and keyup()
, to deal with different events. In addition to the dedicated methods, jQuery also provides a generic on
method which allows you to attach a handler for any event: on('eventName', handler)
. Bear in mind that these methods are just wrappers around standard DOM events, and you could add handlers for these events in plain JavaScript.
In this tutorial we will take a quick look at all these event methods, which are divided into five broad categories, and talk about the best practices to follow when working with them.
Browser Events
There are three events in this category. These are error
, resize
and scroll
. The error
event is fired when elements such as images don’t load properly. Its shortcut method has been deprecated since jQuery version 1.8, so you should now use on('error', handler)
instead.
The Resize Event
This event is triggered whenever the size of browser window changes. Different browsers can call the resize handler differently based on implementation. Internet Explorer and WebKit-based browsers call the handler continuously while browsers like Opera call it only at the end of resize event.
This code snippet below swaps the image src
based on window width.
$(window).resize(function() {
var windowWidth = $(window).width();
if (windowWidth <= 600) {
$("img").attr("src", "image-src-here.jpg");
// Image src changed at this point.
}
});
This CodePen demo shows the event in action:
The Scroll Event
An element can set off this event when a user scrolls to a different position in that specific element. Besides the window
object, any element with a scrollbar can trigger this event. For instance, any element with the overflow
property set to scroll, or any scrollable iframe, can fire this event.
Keep in mind that the handler is called whenever the scroll position changes. The cause of the scrolling is irrelevant. It could be triggered on pressing arrow keys, clicking on or dragging the scrollbar or using the mouse scroll wheel. In the code below, we check if the user has scrolled down more than 500px and perform some actions.
$(window).scroll(function() {
if ($(window).scrollTop() >= 500) {
$("#alert").text("You have scrolled enough!");
// Update the text inside alert box.
}
});
In the CodePen demo below if you keep scrolling and reach near the end you should see a notification telling you that you are almost at the bottom of webpage :
Document Loading Events
jQuery has methods for three events that are fired based on the state of document or DOM. These are load
, unload
and ready
.
load()
can be used to attach a handler to any element which loads an external resource, such as images, scripts, iframes and the window
object itself. The event fires when the element it is attached to, along with all sub-elements, have completely loaded. When used with images it poses a few issues. First is that it does not correctly bubble up the DOM tree. Second issue is that it is neither reliable nor cross browser.
The unload
event is fired when a user is navigating away from the webpage. This can happen because the user clicked on a link, typed a new URL in address bar or closed the browser window. This event is also triggered by a page reload. Please note that using preventDefault()
won’t cancel the unload
event. Moreover, calls to alert()
, confirm()
and prompt()
will be ignored by most browsers inside this event handler, meaning that the code below won’t work:
$( window ).unload(function() {
alert("Please don't leave!"); // Won't work.
});
Both load()
and unload()
are deprecated since version 1.8.
The Ready Event
In most cases, there is no need for all the elements like images to load completely before a script can run without any problems. All you need to make sure is that the DOM hierarchy has been fully constructed. The ready
event takes care of this for you. Any handlers attached to this event are run only after the DOM is ready. Inside the handler you can run your jQuery code or attach event handlers to other elements without any worries.
The CodePen demo below loads a high resolution image. You will notice that the DOM becomes ready before the image loads completely.
If your code depends on the value of some CSS style properties, you should first provide reference to the respective style sheets or embedded styles before running it.
Keyboard Events
Keyboard events can be triggered by any user interaction with the keyboard. Each such event will have information about the key pressed and the event type. There are three keyboard event shortcuts in jQuery — keydown()
, keyup()
and keypress()
.
The Keyup and Keydown Events
As the name suggests, keyup
is fired when a user releases a key on keyboard and keydown
is fired whenever a user presses a key on keyboard. Handlers for both of these events can be attached to any element, but only handlers on the element that currently has focus will be triggered.
It is recommended to use the which
property of the event
object to determine which key was pressed. This is due to the fact that browsers use different properties to store this information and jQuery normalizes the which
property for reliably retrieving this information.
One more thing worth remembering is that both these events make no distinction between a and shift+a. In the latter case, both shift and a are registered separately. In the code below, I present the user with an alert box which registers any keydown
event. When the y key is pressed, a specific element is removed from DOM.
$("#alert").keydown(function(event) {
switch (event.which) {
case 89: // keycode for y
$("#element").remove(); // Remove element from the DOM
break;
}
});
The Keypress Event
This event is just like keydown
event. One major difference is that modifier and non-printing keys like Shift, Esc etc. don’t fire keypress
event. I can’t stress this enough when I say that you should not use keypress
event for catching special keystrokes like arrow keys. keypress
is to be used when you want to know which character was entered, like A
or a
.
The code snippet below hides an element based on the key pressed:
$("body").keypress(function(event) {
switch (event.keyCode) {
case 75:
// 75 stands for capital K in keypress event
$(".K").css("display", "none");
break;
}
});
Mouse Events
Mouse events are fired when a user interacts using a pointing device such as mouse. The events can be based on clicks like click
, dblclick
and contextmenu
or on movement, like mouseenter
, mouseleave
and mousemove
. In this section I will discuss all of them briefly and include some demos to illustrate the minor differences between them.
Click-Based Events
There are five click based event methods defined in jQuery. The mousedown
and mouseup
events, as evident from the names, are fired when a user presses and releases the mouse button over an element respectively. On the other hand, a click
event is fired only when a mouse button is both pressed and later released over the specified element.
dblclick
is slightly more complex. For an event to be registered as dblclick
there should be two quick mouse clicks before a certain system-dependent time interval expires. You should not attach handlers to a single element for both click
and dblclick
simultaneously as the events triggered on a double click are browser specific. Some browsers might register two single click events before the double click one, while others might just register one single click event before the double click.
The contextmenu
event is fired after a right button click on an element but just before displaying the context menu. This implies that you can prevent the default context menu from showing up using the appropriate code in the event handler.
The snippet below prevents the default context menu from showing up on right-click and displays a custom menu instead:
$("img").contextmenu(function(event) {
event.preventDefault();
$("#custom-menu")
.show().css({
top: event.pageY + 10,
left: event.pageX + 10
// Show the menu near the mouse click
});
});
$("#custom-menu #option").click(function() {
$("img").toggleClass("class-name");
// Toggle an image class.
});
This demo applies CSS styles to the image when it’s clicked, and has a custom context menu :
Movement-Based Events
Some events are based on movement of mouse pointer over, or into and out of the element. There are six movement-based event methods.
Let’s start with the mouseover
and mouseenter
events. As the name suggests both these event fire when the mouse pointer enters an element. Similarly, mouseleave
and mouseout
events fire when the mouse pointer leaves an element.
One difference between mouseleave
and mouseout
is that the former is fired only if the mouse pointer moves outside of an element it is bound to. On the other hand, mouseout
is triggered even for movements outside any descendants of that element. The exact same difference exists between mouseenter
and mouseover
.
Let’s look at how the count of mouseenter
and mouseover
events changes based on mouse movements. Try to enter the big blue box from right side and stop right before entering the right pink box. Both mouseenter
and mouseover
should now have value 1. If you move left and enter the pink box, the mouseover
count changes to two. This happens because of event bubbling by mouseover
event. The mouseover
event on the pink box ‘bubbles’ up to outer blue box, increasing count of themouseover
event by 1. When you move further left and stop between both the pink boxes, the mouseover
event fires again. By the time, you reach the left end of blue box, the count of mouseover
event should be 5 and the count of mouseenter
event should still be 1.
The exact same reasoning can be applied to explain the count of mouseleave
and mouseout
events. Try moving around in different direction and see how the count changes.
The Mousemove and Hover Events
The mousemove
event is triggered when mouse pointer moves inside an element. It fires whenever there is mouse movement, even if it is as small as one pixel. Consequently, hundreds of events can be fired in a small time. As you can imagine, performing complex operations inside the event handler can cause browser lag. It is advisable to make the mousemove
event handler as efficient as possible and to unbind it when it is no longer needed.
hover
fires only when the mouse pointer either enters or leaves the element. There are two ways to call the hover
method. The first one is:
$("your-selector").hover( handlerIn, handlerOut );
Here, handlerIn()
is executed when the mouse pointer enters an element and handlerOut()
when mouse pointer leaves it. The second way is:
$("your-selector").hover(handlerInOut);
This time the same handlerInOut
function is executed on both entering and leaving the element.
Form Events
Forms are ubiquitous on the web. Almost every user fills out a form at some point. jQuery has special methods dedicated to handling form events. These events can be triggered on a change in value or loss of focus. There are seven form events and we will discuss them all one by one.
The Blur, Focus, Focusin and Focusout Events
The focus
event is fired whenever an element gains focus. It is applicable only to form elements and anchor tags. To trigger focus
on any other element you will need to set the element’s tabindex
property. Keep in mind that setting focus on hidden elements will result in an error in Internet Explorer. If you have to trigger the focus event without setting the focus explicitly you can call the triggerHandler( "focus" )
method.
The blur
event is triggered whenever an element loses focus. On older browsers this event is only applicable to form elements.
Unlike focus
event, focusin
is fired whenever any element or its descendant gains focus. Similarly, focusout
is fired whenever any element or its descendants lose focus. So, if you want the events to bubble, you should use these two events instead.
The Select, Change and Submit Events
The change
event is fired when an element changes value. This event is applicable only to <input>
, <textarea>
and <select>
elements. In the case of checkboxes, radio buttons and select boxes, this event is fired as soon as a user makes any selection. On other elements it fires only after the element loses focus. Also note that this event won’t be triggered if value of an input element is changed using JavaScript.
The select
event is triggered when a user makes a text selection inside an element. This event more limited in scope and only applies to <input type="text">
and <textarea>
elements. If you want to retrieve the selected text you will have to use a cross-browser jQuery plugin.
The submit
event is fired when a user tries to submit a form. You can only attach handlers to form elements. To trigger this event, users will have to click on <input type="submit">
,<button type="submit">
or <input type="image">
elements. Interestingly, the JavaScript submit
event does not bubble up in Internet Explorer. However, this behavior has been normalized across browsers as of jQuery version 1.4.
Changes in jQuery 3
The load
, error
and unload
methods have been deprecated since jQuery version 1.8. The load()
method is ambiguous in nature. This method could either mean an AJAX load or an actual firing of load event. Similarly, the error
method could also be confused with the jQuery.error()
method. Now in jQuery 3, these methods have finally been removed. You will now have to use the on
method to register these event listeners.