Home > Web Front-end > JS Tutorial > How Does Vanilla JavaScript Event Delegation Compare to jQuery\'s Approach for Optimal Performance?

How Does Vanilla JavaScript Event Delegation Compare to jQuery\'s Approach for Optimal Performance?

Barbara Streisand
Release: 2024-11-26 10:05:15
Original
235 people have browsed it

How Does Vanilla JavaScript Event Delegation Compare to jQuery's Approach for Optimal Performance?

Event Delegation in Vanilla JavaScript for Optimal Performance

Revisiting the jQuery Syntax

In jQuery, event delegation can be achieved using the following code:

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

Translating to Vanilla JavaScript

Utilizing event delegation in vanilla JavaScript can be achieved through addEventListener. However, it's important to optimize the approach for efficiency. Consider the following alternative:

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

By utilizing closest(), we check if the clicked element or any of its ancestors matches the .focused selector. This eliminates the need for inefficiently iterating through child elements.

Keeping Code Compact

To enhance code compactness, the main logic can be placed below an early return statement:

document.querySelector('#main').addEventListener('click', (e) => {
  if (!e.target.closest('.focused')) {
    return;
  }

  // Code of settingsPanel here
});
Copy after login

Example Implementation

The following code demonstrates the approach:

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

Observe the output when interacting with the elements with both vanilla JavaScript and jQuery event handlers.

The above is the detailed content of How Does Vanilla JavaScript Event Delegation Compare to jQuery\'s Approach for Optimal Performance?. 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