In jQuery, event delegation can be achieved using the following code:
$('#main').on('click', '.focused', function() { settingsPanel(); });
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.
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 });
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!