Today I Learned - Rocky Kev

TIL adding an Event Listener to document

POSTED ON:

TAGS:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.