亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Key Points
Browser Events
scrollEvent
Document Loading Event
readyEvent
Keyboard Events
keyup and keydown Events
keypressEvent
Mouse Event
Click-based events
Mobile-based events
mousemove and hover Events
, blur, focus, focusin and focusout Events
select, change and submit Events
Changes in jQuery 3
The final thought
FAQ for jQuery Events (FAQ)
How to prevent events in jQuery from bubbled?
and .bind() methods in .live()?
How to trigger an event programmatically in jQuery?
What is the event delegate in jQuery and why is it useful?
How to block the default operation of events in jQuery?
What is the difference between .click() and .on('click') in jQuery?
How to detect double-click event in jQuery?
How to bind multiple events to elements in jQuery?
How to unbind event handler in jQuery?
How to detect right-click event in jQuery?
Home Web Front-end JS Tutorial A Comprehensive Look at Events in jQuery

A Comprehensive Look at Events in jQuery

Feb 18, 2025 am 09:08 AM

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。
  }
});

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。
  }
});

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("您已經(jīng)滾動(dòng)足夠了!");
    // 更新警報(bào)框內(nèi)的文本。
  }
});

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。
  }
});

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("您已經(jīng)滾動(dòng)足夠了!");
    // 更新警報(bào)框內(nèi)的文本。
  }
});

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。
  }
});

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。
  }
});

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("您已經(jīng)滾動(dòng)足夠了!");
    // 更新警報(bào)框內(nèi)的文本。
  }
});
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。
  }
});
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。
  }
});

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("您已經(jīng)滾動(dòng)足夠了!");
    // 更新警報(bào)框內(nèi)的文本。
  }
});

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("請(qǐng)不要離開!"); // 不起作用。
});

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;
  }
});

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;
  }
});

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
      // 在鼠標(biāo)點(diǎn)擊附近顯示菜單
    });
});

$("#custom-menu #option").click(function() {
   $("img").toggleClass("class-name");
   // 切換圖像類。
});

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does garbage collection work in JavaScript? How does garbage collection work in JavaScript? Jul 04, 2025 am 12:42 AM

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. Jul 08, 2025 pm 02:27 PM

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

React vs Angular vs Vue: which js framework is best? React vs Angular vs Vue: which js framework is best? Jul 05, 2025 am 02:24 AM

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Understanding Immediately Invoked Function Expressions (IIFE) in JavaScript Jul 04, 2025 am 02:42 AM

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

What is the cache API and how is it used with Service Workers? What is the cache API and how is it used with Service Workers? Jul 08, 2025 am 02:43 AM

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Jul 08, 2025 am 02:40 AM

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

See all articles