Event Delegation with Vanilla JavaScript
In vanilla JavaScript, event delegation is a technique used to attach event listeners to a single parent element instead of individual elements within it. This approach improves performance by eliminating the need for multiple event listeners and simplifies the code.
Effective Event Delegation
To implement event delegation efficiently, use the following steps:
Example: Delegating jQuery Code
Consider the following jQuery code:
$('#main').on('click', '.focused', function() { settingsPanel(); });
To translate this code to vanilla JavaScript, use the following:
document.querySelector('#main').addEventListener('click', (e) => { if (e.target.closest('.focused')) { settingsPanel(); } });
In this code, we use querySelector() to find the parent element with the ID main and attach a click event listener to it. When an element within this parent is clicked, it checks if the clicked element or any of its parent elements have the .focused class. If so, it invokes the settingsPanel() function.
Benefits of Delegating:
The above is the detailed content of How Can Event Delegation Improve Vanilla JavaScript Performance and Code Simplicity?. For more information, please follow other related articles on the PHP Chinese website!