Home > Web Front-end > JS Tutorial > A Comprehensive Look at Events in jQuery

A Comprehensive Look at Events in jQuery

Jennifer Aniston
Release: 2025-02-18 09:08:11
Original
352 people have browsed it

A Comprehensive Look at Events in jQuery

This article was reviewed by Wern Ancheta and Camilo Reyes. Thanks to all the peer reviewers at SitePoint for getting SitePoint content to its best!

jQuery is able to capture almost all user interaction behaviors in a web page and define it as events. The importance of events is that they allow you to respond accordingly based on the actions of the user. For example, you can write code to change the background color of a web page based on button clicks or scroll events.

jQuery has many quick methods, such as contextmenu(), hover() and keyup(), for handling different events. In addition to the dedicated methods, jQuery also provides a common on method that allows you to attach handlers to any event: on('eventName', handler). Remember, these methods are just wrappers for standard DOM events that you can add handlers to in pure JavaScript.

This tutorial will quickly look at all these event methods (divided into five major categories) and discuss best practices when using them.

Key Points

  • jQuery events capture user interactions, enabling responsive and interactive web applications. Use methods like .on() to attach event handlers.
  • Browser events in jQuery include handling errors, resize windows, and scrolling, where certain specific methods in newer versions are deprecated, emphasizing the use of .on('eventName', handler)'.
  • Document loading event ensures that the script only runs after the DOM is fully ready, avoiding errors related to uninitialized elements.
  • Keyboard and mouse events in jQuery handle a variety of interactions, from key presses to mouse movement, including keydown(), keyup(), click(), and mousemove().
  • Form Events handle user input and interactions within a form, jQuery provides dedicated events to effectively manage focus, changes, and submissions.

Browser Events

This category contains three events: error, resize and scroll. The error event is triggered when elements such as images are loaded incorrectly. Its shortcut method has been deprecated since jQuery version 1.8, so you should now use on('error', handler) instead.

resizeEvent

This event is triggered whenever the size of the browser window changes. Different browsers can call the resize handler in different ways according to the implementation method. Internet Explorer and WebKit-based browsers call handlers continuously, while browsers like Opera only call it when the resize event ends.

The following code snippet swaps images based on the window width src.

$(window).resize(function() {
  var windowWidth = $(window).width();
  if (windowWidth < 768) {
    $("img").attr("src", "image-src-here.jpg");
    // 此处更改图像src。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

This CodePen demonstration shows the actual effect of the event:

View CodePen demo

scrollEvent

Element can trigger this event when the user scrolls to different positions in a specific element. Except for the window object, any element with a scroll bar can trigger this event. For example, any element that sets the overflow attribute to scroll or any scrollable iframe can trigger this event.

Remember that the handler is called whenever the scroll position changes. The cause of the scroll doesn't matter. It can be triggered by pressing the arrow key, clicking or dragging the scrollbar, or using the mouse wheel. In the code below, we check if the user scrolls down more than 500 pixels and performs some operations.

$(window).resize(function() {
  var windowWidth = $(window).width();
  if (windowWidth < 768) {
    $("img").attr("src", "image-src-here.jpg");
    // 此处更改图像src。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

In the CodePen demo below, if you continue scrolling and reaching near the bottom, you should see a notification telling you that you have almost reached the bottom of the page:

View CodePen demo

Document Loading Event

jQuery has three methods, which are triggered according to the status of the document or DOM. They are load, unload and ready.

load() can be used to attach a handler to any element that loads external resources such as images, scripts, iframes, and window objects themselves. The event is fired when the element it attaches and all its child elements are fully loaded. When used with images, it brings some problems. First, it won't bubble up the DOM tree correctly. The second problem is that it is neither reliable nor cross-browser.

When the user leaves from the web navigation, the unload event is triggered. This may be because the user clicked the link, typed a new URL into the address bar, or closed the browser window. Page reloading also triggers this event. Please note that using preventDefault() will not cancel the unload event. Additionally, most browsers ignore calls to alert(), confirm() and prompt() inside this event handler, which means the following code will not work:

$(window).scroll(function() {
  if ($(window).scrollTop() >= 500) {
    $("#alert").text("您已经滚动足够了!");
    // 更新警报框内的文本。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login

Both load() and unload() have been deprecated since version 1.8.

readyEvent

In most cases, all elements (such as images) need not be fully loaded until the script can run without any problem. What you need to make sure is that the DOM hierarchy is fully built. The ready event handles this for you. Any handlers attached to this event will only be run after the DOM is ready. Inside the handler, you can run jQuery code or attach the event handler to other elements without worrying about it.

The CodePen demonstration below loads high resolution images. You will notice that the DOM is ready before the image is fully loaded.

View CodePen demo

If your code depends on the value of some CSS style properties, you should first provide a reference to the corresponding stylesheet or embedded style before running it.

Keyboard Events

Keyboard events can be triggered by any user's interaction with the keyboard. Each such event will contain information about the key press and event type. There are three keyboard event shortcuts in jQuery - keydown(), keyup() and keypress().

keyup and keydown Events

As the name suggests, keyup will be triggered when the user releases the key on the keyboard; keydown will be triggered when the user presses the key on the keyboard. The handler for both events can be attached to any element, but only the handler on the element currently with focus will be triggered.

It is recommended to use the which attribute of the event object to determine which key is pressed. This is because the browser uses different properties to store this information, and jQuery normalizes the which attribute to reliably retrieve this information.

Another thing worth remembering is that the two events do not distinguish between <kbd>a</kbd> and <kbd>shift a</kbd>. In the latter case, <kbd>shift</kbd> and <kbd>a</kbd> are registered separately. In the code below, I show the user an alert box that registers any keydown events. When the <kbd>y</kbd> key is pressed, a specific element is deleted from the DOM.

$(window).resize(function() {
  var windowWidth = $(window).width();
  if (windowWidth < 768) {
    $("img").attr("src", "image-src-here.jpg");
    // 此处更改图像src。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

View CodePen demo

keypressEvent

This event is similar to the keydown event. One major difference is that modifiers and non-print keys (such as <kbd>Shift</kbd>, <kbd>Esc</kbd>, etc.) do not trigger the keypress event. When I say you shouldn't use the keypress event to capture special keys (such as arrow keys), I can't put it too much. When you want to know which character (such as A or a) you have entered, you should use keypress.

The following code snippet hides elements based on the key pressed:

$(window).scroll(function() {
  if ($(window).scrollTop() >= 500) {
    $("#alert").text("您已经滚动足够了!");
    // 更新警报框内的文本。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login

View CodePen demo

Mouse Event

A mouse event is triggered when the user interacts with a pointing device (such as a mouse). These events can be based on clicks (such as click, dblclick and contextmenu) or based on mobile (such as mouseenter, mouseleave and mousemove). In this section, I will briefly discuss all of these events and include some demonstrations to illustrate the slight differences between them.

Click-based events

JQuery defines five click-based event methods. The mousedown and mouseup events (as can be seen from the name) are fired when the user presses and releases the mouse button on the element, respectively. On the other hand, the click event is triggered only when the mouse button is pressed on the specified element and subsequently released.

dblclickSlightly complicated. For events to be registered as dblclick, there should be two quick mouse clicks before a system-related counting interval expires. You should not attach the handler to both click and dblclick of a single element, because the events triggered by a double-click are browser-specific. Some browsers may register two single click events before double-clicking, while others may register only one single click event before double-clicking.

The contextmenu event is triggered after right-clicking on the element but before the context menu is displayed. This means you can use the corresponding code in the event handler to prevent the default context menu from displaying.

The following code snippet prevents the default context menu from being displayed when right-clicked, but instead displays a custom menu:

$(window).resize(function() {
  var windowWidth = $(window).width();
  if (windowWidth < 768) {
    $("img").attr("src", "image-src-here.jpg");
    // 此处更改图像src。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

This demo applies CSS style to the image when clicking an image and has a custom context menu:

View CodePen demo

Mobile-based events

Some events are based on the movement of the mouse pointer on, entering or removing an element. There are six mobile-based event methods.

Let's start with the mouseover and mouseenter events. As the name implies, both events are fired when the mouse pointer enters an element. Similarly, when the mouse pointer leaves the element, the mouseleave and mouseout events are fired.

One difference between

mouseleave and mouseout is that the former is fired only when the mouse pointer moves outside the element that binds it. On the other hand, even for movement outside of any descendants of the element, mouseout will be triggered. There is exactly the same difference between mouseenter and mouseover.

View CodePen demo

Let's see how the event counts change based on mouse movement, mouseenter and mouseover. Try entering the large blue box from the right and stop before entering the pink box on the right. mouseenter and mouseover should now both have values ​​of 1. If you move left and enter the pink box, the mouseover count will change to 2. This happens because the event of mouseover is bubbling. The mouseover event on the pink box "bubles" to the outer blue box, increasing the count of the mouseover event by 1. The mouseover event fires again when you move further to the left and stops between the two pink boxes. When you reach the left end of the blue box, the count of the mouseover event should be 5, and the count of the mouseenter event should still be 1.

The exact same reasoning can be used to explain the count of mouseleave and mouseout events. Try moving in different directions and see how the count changes.

mousemove and hover Events

When the mouse pointer moves within the element, the mousemove event is triggered. As long as there is a mouse moving, it will trigger even if it is as small as a pixel. Therefore, hundreds of events can be triggered in a very short time. As you can imagine, performing complex operations in an event handler will cause a browser to lag. It is recommended to make the mousemove event handler as efficient as possible and unbind it if it is no longer needed.

hoverFree only when the mouse pointer enters or leaves the element. There are two ways to call the hover method. The first one is:

$(window).resize(function() {
  var windowWidth = $(window).width();
  if (windowWidth < 768) {
    $("img").attr("src", "image-src-here.jpg");
    // 此处更改图像src。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Here, when the mouse pointer enters the element, handlerIn() is executed when the mouse pointer leaves the element. The second method is: handlerOut()

$(window).scroll(function() {
  if ($(window).scrollTop() >= 500) {
    $("#alert").text("您已经滚动足够了!");
    // 更新警报框内的文本。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login
This time, the same

function will be executed when entering and leaving the element. handlerInOut

View CodePen demo

Note: This demonstration uses CSS filter effect, which IE does not support.

Form Events

Forms are everywhere on the Internet. Almost every user fills out the form at some point. jQuery has a special way to handle form events. These events can be fired when the value changes or loses focus. There are seven form events in total, and we will discuss them one by one.

, blur, focus, focusin and focusout Events

Whenever an element gains focus, the focus event is triggered. It only works with form elements and anchor tags. To trigger focus on any other element, you need to set the tabindex attribute of the element. Remember that in Internet Explorer, setting focus on hidden elements can cause an error. If you have to trigger the focus event without explicitly setting the focus, you can call the triggerHandler("focus") method.

Whenever the element loses focus, the blur event is triggered. In older browsers, this event applies only to form elements.

Unlike focus events, focusin is triggered whenever any element or its descendants gain focus. Similarly, focusout is triggered whenever any element or its descendants lose focus. So if you want the event to bubble up, you should use both events.

select, change and submit Events

When the value of an element changes, the change event is triggered. This event only applies to <input>, <select> and <textarea> elements. For check boxes, radio buttons, and selection boxes, this event is triggered immediately after the user makes any selections. On other elements, it will only fire after the element loses focus. Also note that if you change the value of the input element using JavaScript, this event will not be triggered.

When the user makes text selections within the element, the select event is triggered. This event has a more limited scope and is only applicable to <input> and <textarea> elements. If you want to retrieve selected text, you must use a cross-browser jQuery plugin.

When the user tries to submit a form, the submit event is triggered. You can only attach handlers to form elements. To trigger this event, the user must click the <button>, <input type="submit"> or <input type="image"> element. Interestingly, JavaScript submit events do not bubble up in Internet Explorer. However, this behavior has been standardized in the browser since jQuery version 1.4.

View CodePen demo

Changes in jQuery 3

Since jQuery version 1.8, the load, error and unload methods have been deprecated. load()The method is inherently unclear. This method may mean AJAX loads or actually fired load events. Similarly, the error method may also be confused with the jQuery.error() method. Now in jQuery 3, these methods have finally been removed. You must now use the on method to register these event listeners.

The final thought

In this article, I have covered the differences between all the main jQuery event methods and similar events. Knowing when to use keypress instead of keydown can help you avoid hassle and save valuable time. While it is possible to connect to DOM events using pure JavaScript, jQuery does have some normalization of the cross-browser differences in the background, depending on which browsers your website/application must support, which may be an advantage.

To learn more about events, you can access the official jQuery documentation. If you have any questions or tips about using events in jQuery please leave a comment.

FAQ for jQuery Events (FAQ)

How to prevent events in jQuery from bubbled?

In jQuery, you can use the event.stopPropagation() method to prevent events from bubble upwards of the DOM tree. This method prevents events from propagating to the parent element. It should be noted that it does not prevent any default behavior from happening; it just prevents events from bubbled up. Here is an example of how to use it:

$(window).resize(function() {
  var windowWidth = $(window).width();
  if (windowWidth < 768) {
    $("img").attr("src", "image-src-here.jpg");
    // 此处更改图像src。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
What is the difference between

and .bind() methods in .live()?

The

and .bind() methods in .live()jQuery are both used to attach an event handler to an element. The main difference between them is that .bind() only attaches the handler to the current element, while .live() attaches the handler to the current element and all elements that match the selector in the future. However, it is worth noting that the .live() method has been deprecated since jQuery 1.7 and has been removed in jQuery 1.9. You should use the .on() method instead.

How to trigger an event programmatically in jQuery?

You can use the .trigger() method to trigger events programmatically in jQuery. This method allows you to manually trigger a specified event on an element. Here is an example:

$(window).resize(function() {
  var windowWidth = $(window).width();
  if (windowWidth < 768) {
    $("img").attr("src", "image-src-here.jpg");
    // 此处更改图像src。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

What is the event delegate in jQuery and why is it useful?

Event delegation in jQuery is a technique in which you delegate the processing of an event to the parent element instead of binding the event handler to the individual elements. This is especially useful when you have a large number of elements that require an event handler like, or when you dynamically add elements to the DOM. It improves performance by reducing the number of event handlers that need to be bound.

How to block the default operation of events in jQuery?

You can use the event.preventDefault() method to block the default operation of events in jQuery. This method prevents the default operation of the event from happening. For example, it can prevent links from following URLs.

$(window).scroll(function() {
  if ($(window).scrollTop() >= 500) {
    $("#alert").text("您已经滚动足够了!");
    // 更新警报框内的文本。
  }
});
Copy after login
Copy after login
Copy after login
Copy after login

What is the difference between .click() and .on('click') in jQuery?

The .click() method in jQuery is the abbreviation of .on('click'). Both methods attach the click event handler to the selected element. However, the .on() method provides greater flexibility because it can also handle events of dynamically added elements and can handle multiple events at once.

How to detect double-click event in jQuery?

You can use the .dblclick() method to detect double-click events in jQuery. This method attaches a function that executes when a double-click event occurs on the selected element. Here is an example:

$(window).unload(function() {
  alert("请不要离开!"); // 不起作用。
});
Copy after login

How to bind multiple events to elements in jQuery?

You can use the .on() method to bind multiple events to elements in jQuery. This method allows you to attach multiple event handlers to the selected element. Here is an example:

$("#alert").keydown(function(event) {
  switch (event.which) {
    case 89: // y的键码
      $("#element").remove(); // 从DOM中删除元素
      break;
  }
});
Copy after login

How to unbind event handler in jQuery?

You can use the .off() method to unbind the event handler in jQuery. This method removes the event handler attached using .on(). Here is an example:

$("body").keypress(function(event) {
  switch (event.keyCode) {
    case 75:
      // 75在keypress事件中代表大写K
      $(".K").css("display", "none");
      break;
  }
});
Copy after login

How to detect right-click event in jQuery?

You can use the .contextmenu() method or check the "which" property of the event object in the mousedown event to detect the right-click event in jQuery. The "which" property will be 3 for right clicks. Here is an example:

$("img").contextmenu(function(event) {
  event.preventDefault();
  $("#custom-menu")
    .show().css({
      top: event.pageY + 10,
      left: event.pageX + 10
      // 在鼠标点击附近显示菜单
    });
});

$("#custom-menu #option").click(function() {
   $("img").toggleClass("class-name");
   // 切换图像类。
});
Copy after login

The above is the detailed content of A Comprehensive Look at Events in jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template