Event delegation is a technique used to simplify the handling of multiple event listeners attached to different elements within a DOM structure. In vanilla JavaScript, this can be achieved using .addEventListener().
To translate the jQuery example provided in the question:
$('#main').on('click', '.focused', function() { settingsPanel(); });
... into vanilla JavaScript, we would use:
document.querySelector('#main').addEventListener('click', (e) => { if (e.target.closest('#main .focused')) { settingsPanel(); } });
However, to optimize performance and avoid excessive DOM traversal, it's recommended to pass only the inner selector to .closest():
document.querySelector('#main').addEventListener('click', (e) => { if (e.target.closest('.focused')) { settingsPanel(); } });
For readability, it's common to check for the condition within an early return statement:
document.querySelector('#main').addEventListener('click', (e) => { if (!e.target.closest('.focused')) { return; } // Remaining code of settingsPanel here });
Compared to the alternative solution provided in the question (document.getElementById('main').addEventListener('click', doThis);), this method offers improved performance, as it employs event bubbling and avoids iterating through numerous child elements within #main.
To illustrate the difference, you can refer to the live demo snippet provided in the answer. Upon clicking the inner element (#inner), both the vanilla JavaScript and jQuery event handlers will log their respective messages to the console.
The above is the detailed content of How Does Vanilla JavaScript Event Delegation Improve Performance over Multiple Individual Event Listeners?. For more information, please follow other related articles on the PHP Chinese website!