TIL adding an Event Listener to document
POSTED ON:
TAGS: javascript click performance
How it works under the hood #
When an element in the DOM is clicked, the event bubbles all the way up to the parent element (the document and then the window). This allows you to listen for events on the parent item and still detect clicks that happen inside it.
Listening to multiple events #
To listen to multiple events --
In the jQuery days, you would do stuff like this.
// can be one element or thousands
$('.click-me').click(function (event) {
// Do things...
});
To do it in Javascript, you have to use a loop.
var clickMe = document.querySelectorAll('.click-me');
for (var i = 0; i < clickMe.length; i++) {
clickMe[i].addEventListener('click', function (event) {
// Do stuff...
}, false);
}
Performance #
Listening to every event in the document
is more performant than individual event listeners on elements.
You can even add conditionals:
document.addEventListener('click', function (event) {
if (event.target.matches('.modal-open')) {
// Run your code to open a modal
}
if (event.target.matches('.close')) {
// Run your code to close a modal
}
}, false);
via Why event delegation is a better way to listen for events in vanilla JS
Related TILs
Tagged: javascript