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
Barbara StreisandOriginal
2024-11-26 10:05:15183browse

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

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

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

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

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!

Statement:
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