Home > Article > Web Front-end > How Can I Effectively Implement Event Delegation in Vanilla JavaScript?
Event Delegation in Vanilla JavaScript: A Comprehensive Guide
Achieving event delegation in vanilla JavaScript provides an efficient and maintainable way to handle event listeners. Unlike jQuery's event delegation, which involves modifying built-in prototypes, vanilla JavaScript offers a more robust approach through the use of event delegation with '.closest()'.
Translating jQuery Event Delegation to Vanilla JavaScript
To translate the jQuery example:
$('#main').on('click', '.focused', function(){ settingsPanel(); });
Into vanilla JavaScript, we use:
document.querySelector('#main').addEventListener('click', (e) => { if (e.target.closest('.focused')) { settingsPanel(); } });
The '.closest()' method checks if the clicked element has a parent element that matches the '.focused' selector. If so, it invokes the 'settingsPanel()' function.
Optimization for Complex Event Chaining
To enhance performance, especially when dealing with nested elements, consider using an early return:
document.querySelector('#main').addEventListener('click', (e) => { if (!e.target.closest('.focused')) { return; } // code of settingsPanel here, if it isn't too long });
This approach prevents unnecessary code execution when the '.focused' selector is not matched.
Live Demonstration
The following code snippet showcases how to use vanilla JavaScript's event delegation with '.closest()':
document.querySelector('#outer').addEventListener('click', (e) => { if (!e.target.closest('#inner')) { return; } console.log('vanilla'); }); $('#outer').on('click', '#inner', () => { console.log('jQuery'); });
In this example, clicking on the '#inner' element will log "vanilla" to the console, demonstrating vanilla JavaScript's event delegation.
The above is the detailed content of How Can I Effectively Implement Event Delegation in Vanilla JavaScript?. For more information, please follow other related articles on the PHP Chinese website!