Home > Web Front-end > JS Tutorial > How Can Event Delegation with `closest()` Optimize Vanilla JavaScript Event Handling?

How Can Event Delegation with `closest()` Optimize Vanilla JavaScript Event Handling?

Patricia Arquette
Release: 2024-11-29 13:04:11
Original
573 people have browsed it

How Can Event Delegation with `closest()` Optimize Vanilla JavaScript Event Handling?

Vanilla JavaScript Event Delegation: An Efficient and Proper Approach

Event delegation is a common technique in JavaScript that allows you to attach event listeners to a single parent element and delegate event handling to its child elements. This approach can significantly improve performance by avoiding redundant event listener creation for each individual child.

One common way to implement event delegation in vanilla JavaScript is through the addEventListener() method. However, the implementation mentioned in the question, which involves traversing through all of #main's children, is not optimal for performance.

A more efficient alternative is to utilize the closest() method, which checks if a clicked element has a parent element that matches a specified selector. This allows you to delegate events more accurately and efficiently.

For example, to translate the jQuery event handler into vanilla JavaScript using closest():

document.querySelector('#main').addEventListener('click', (e) => {
  if (e.target.closest('#main .focused')) {
    settingsPanel();
  }
});
Copy after login

In this code, we first select the #main element and add an event listener for the 'click' event. When a click occurs, we use closest() to check if the clicked element has a parent element with the '.focused' class. If it does, we invoke the settingsPanel() function.

This approach is efficient because it only checks the necessary elements and does not require iterating through all of #main's children. Additionally, it reduces fragile dependencies by directly referencing the target element.

When working with deeply nested structures, ensuring that the inner selector cannot also be a parent element can further optimize performance. Live demos and additional details regarding this approach are provided in the given reference material.

The above is the detailed content of How Can Event Delegation with `closest()` Optimize Vanilla JavaScript Event Handling?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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