Home > Web Front-end > JS Tutorial > How Can I Effectively Implement Event Delegation in Vanilla JavaScript?

How Can I Effectively Implement Event Delegation in Vanilla JavaScript?

DDD
Release: 2024-11-24 08:25:10
Original
211 people have browsed it

How Can I Effectively Implement Event Delegation in Vanilla JavaScript?

Event Delegation in Vanilla JavaScript: A Comprehensive Guide

Achieving event delegation in vanilla JavaScript provides an efficient and maintainable way to handle event listeners. Unlike jQuery's event delegation, which involves modifying built-in prototypes, vanilla JavaScript offers a more robust approach through the use of event delegation with '.closest()'.

Translating jQuery Event Delegation to Vanilla JavaScript

To translate the jQuery example:

$('#main').on('click', '.focused', function(){
    settingsPanel();
});
Copy after login

Into vanilla JavaScript, we use:

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

The '.closest()' method checks if the clicked element has a parent element that matches the '.focused' selector. If so, it invokes the 'settingsPanel()' function.

Optimization for Complex Event Chaining

To enhance performance, especially when dealing with nested elements, consider using an early return:

document.querySelector('#main').addEventListener('click', (e) => {
  if (!e.target.closest('.focused')) {
    return;
  }
  // code of settingsPanel here, if it isn't too long
});
Copy after login

This approach prevents unnecessary code execution when the '.focused' selector is not matched.

Live Demonstration

The following code snippet showcases how to use vanilla JavaScript's event delegation with '.closest()':

document.querySelector('#outer').addEventListener('click', (e) => {
  if (!e.target.closest('#inner')) {
    return;
  }
  console.log('vanilla');
});

$('#outer').on('click', '#inner', () => {
  console.log('jQuery');
});
Copy after login

In this example, clicking on the '#inner' element will log "vanilla" to the console, demonstrating vanilla JavaScript's event delegation.

The above is the detailed content of How Can I Effectively Implement Event Delegation in Vanilla JavaScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template