Home > Web Front-end > JS Tutorial > Event Delegation with jQuery

Event Delegation with jQuery

Joseph Gordon-Levitt
Release: 2025-02-24 09:22:11
Original
618 people have browsed it

Event Delegation with jQuery

Core points

  • Event delegates in jQuery are a technique for attaching a single event handler to a parent element instead of multiple handlers attached to individual elements, thereby reducing memory usage and improving performance.
  • jQuery functionon() can be used to implement event delegate, and the optional second parameter specifies the selector for delegate event handler. Then use the event.target attribute to identify which element triggered the event.
  • In dynamic applications, elements are often added or removed, and event delegates are especially useful because it eliminates the need to manage events manually and reduces code complexity. However, it should be noted that the sub-event handler handles before delegating the event handler and may prevent the event from propagating.

jQuery simplifies event handling in JavaScript. However, the more event handlers are defined, the more memory is used, which will eventually lead to performance degradation and slow down the UI. This article explores how event delegates can help prevent this, and how event delegates can be applied in jQuery. Event delegates are an event processing technique that instead of appending an event handler directly to each element that is to listen for an event, it appends a single event handler to the parent element of these elements to listen for happening on its child elements. events. When processing an event, check which element triggers the event and responds accordingly. Event delegates depend on event bubbles in the DOM. This is the process of events triggered on children propagating up to the DOM tree to its parent element and its parent element, etc. until it reaches the document. Programmers can use event.stopPropagation() to stop bubbling. Note that not all DOM events will propagate—focus, blur, load, and unload will not. Event delegates use less memory because you replace multiple event handlers with a single event handler. For example, if you attach an event handler to each link in the list of ten links, there will be ten event handlers taking up memory space. Instead, if you use event delegates and handle events at the parent element, only one event handler is created and less memory is used than the memory attached to each link separately. In addition to reducing memory consumption, event delegation also has the following advantages:

  • No need to manually manage events when adding elements to or removing elements from DOM. If we use traditional event handling, we must attach the event handler to the element added to the DOM and remove the event handler from the element removed from the DOM.
  • Reduce the code to be managed with fewer event handlers. This can make our code simpler without any duplicate event handling logic, which helps keep our JavaScript concise and DRY.

Example of event delegation in jQuery

Suppose you are developing a single page application that sells kitten pictures. When the page loads, the top 20 kittens will be displayed. When the user scrolls down the page, more kittens will be loaded. Our HTML looks like this:

<div id="cats">
  <ul>
    <li>
      <img src="/static/imghw/default1.png"  data-src="https://img.php.cn/"  class="lazy" alt=""/>
      <a href="https://www.php.cn/link/207f170979dd72ff5776e20d07c28732">More info</a>
      <button>Add to cart</button>
    </li>
    ...
  </ul>
</div>
Copy after login

Using traditional event handling, we need to connect the event handler to:

  1. A larger image is displayed when the user clicks on the thumbnail.
  2. More information is displayed when the user clicks the "More Information" link.
  3. Add the image to the cart when the user clicks "Add to Cart".
  4. Attach these three events to the new DOM element added when the user scrolls down the page.

This code will be similar to the following example. Note that this is intended to show how appending an event handler to individual elements differs from using event delegates, so there is no implementation provided for loadImage(), moreInfo(), addToCart(), and loadNewKittens() functions.

$(document).ready(function() {
  var cats = $('#cats');

  cats.find('img')
    .on('click', function() {
      loadImage();
    })

  cats.find('a')
    .on('click', function(event) {
      event.preventDefault();
      moreInfo();
    });

  cats.find('button')
    .on('click', function() {
      addToCart();
    });

  $(window).scroll(function() {
    var fragment = loadNewKittens();
    // 为新的DOM元素附加事件处理程序
    fragment.find('img')
      .on('click', function() {
        loadImage();
      });

    fragment.find('a')
      .on('click', function(event) {
        event.preventDefault();
        moreInfo();
      });

    fragment.find('button')
      .on('click', function() {
        addToCart();
      });

    fragment.appendTo('#cats ul');
  });
});
Copy after login

The code volume is quite large. Now let's see what our code looks like if we use event delegates:

$(document).ready(function() {
  $('#cats')
    .on('click', 'img, a, button', function(event) {
      event.preventDefault();
      var target = event.target;

      switch(target.tagName.toLowerCase()) {
        case 'img':
          loadImage();
          break;
        case 'a':
          moreInfo();
          break;
        case 'button':
          addToCart();
          break;
        default:
          // 什么也不做
      }
    });

  $(window).scroll(function() {
    var fragment = loadNewKittens();
    fragment.appendTo('#cats ul');
  });
});
Copy after login

The key lies in the optional second parameter of on(). By passing the selector here, on() knows that it is handling the delegate event handler instead of the directly bound event handler. Our event handling code is much simpler now. By getting event.target and switching based on its tagName, we can determine which element triggered the event and respond accordingly. Additionally, we no longer need to attach event handlers to elements loaded in $(window).scroll, because events triggered by these new elements are delegated to the parent element. A potential "trap" to be noted when using event delegates is that any event handler attached to a child element is handled before the delegate event handler triggers . Therefore, the sub-event handler may call or return event.stopPropagation(), which will prevent the event from bubbled into the delegate event handler and leave you puzzled as to why your event is not delegated. false

Conclusion

In this article, we study event delegation. We've seen how it can help improve the performance of a website by reducing the event processing load it has to bear. We also saw how to implement event delegate in jQuery through the

function. on()

Frequently Asked Questions about jQuery Event Delegation

What is event delegate in jQuery and why it matters?

Event delegates in jQuery are a technique that allows you to attach a single event listener to the parent element, which will fire for all descendants of matching selectors, whether those descendants exist now or are added in the future. This is important because it can greatly improve performance by reducing the number of event handlers required by the application. Instead of appending individual event handlers to each element, you can delegate events to parent elements. This is especially useful in dynamic applications where elements are added or removed dynamically.

How does event delegation work in jQuery?

Event delegates in jQuery take advantage of the fact that most jQuery events will bubble or propagate up to the DOM tree. When an event is fired on a child element, it will bubble to its parent element. By appending an event listener to the parent element, you can capture events triggered on any of its child elements. The event.target attribute can be used to determine which child element triggered the event.

What is the difference between direct events and delegated events in jQuery?

Direct events are directly attached to specific elements, and only these elements can trigger events. On the other hand, delegate events are attached to the parent element, and any child element can trigger events. The advantage of delegate events is that they can handle events of dynamically added child elements.

How to use the .on() method to perform event delegation in jQuery?

The .on() method in jQuery is used to attach event handlers. For event delegates, you will use three parameters: event type, selector string used to filter descendants, and handler functions. An event type is a string representing the event type (for example, "click"), a selector string is used to filter descendants of the selected element that triggers the event, and a handler function is a function to be executed when the event is triggered.

Can I use event delegate to handle dynamically added elements in jQuery?

Yes, one of the main advantages of event delegates in jQuery is that it can handle events of elements that are dynamically added. Since the event listener is attached to the parent element, it can capture events triggered on any of its child elements, even if those events are added after the event listener is attached.

What is event bubble, and what does it have to do with event delegation in jQuery?

Event bubble is an event propagation type in which an event starts with the specific element that triggers it and then bubbles to its ancestors. Event delegates in jQuery use event bubbles to attach event listeners to parent elements. When an event is fired on a child element, it will bubble to the parent element, where the event listener can capture it.

How to stop event propagation in jQuery?

You can use the .stopPropagation() method to stop event propagation in jQuery. This method prevents events from bubbled into the DOM tree, thus preventing any parent handler from receiving event notifications. However, you should use it with caution as it will make your code harder to debug and understand.

What is the difference between

and .bind() methods used for event processing in jQuery? .on()

The

method in jQuery is used to attach an event handler directly to an element. On the other hand, the .bind() method can be used to attach an event handler directly to an element (such as .on()) or to a parent element for event delegating. The .bind() method is more general and is the preferred method for attaching event handlers in jQuery. .on()

Can I use event delegate to handle custom events in jQuery?

Yes, you can use event delegate to handle custom events in jQuery. Like standard events, you can attach an event listener to a parent element, which will capture custom events triggered on any of its children.

How to delete event handler in jQuery?

You can use the .off() method to delete the event handler in jQuery. This method can be used to delete all event handlers on an element, or to delete only event handlers with a specific event type or namespace attached.

The above is the detailed content of Event Delegation with 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