Today I Learned - Rocky Kev

TIL event bubbling

POSTED ON:

TAGS:

Event bubbling is when an event is in an element inside another element, and both elements have registered a handle to that event.

For example: You have a button. Clicking that button makes it say "Hello". But ou also have events attached to the parent that says "goodbye". Both will trigger!

You can actually see it here:

See the Pen Event bubbling and capturing by Karolis (@karolis) on CodePen.

This stuff can get kinda hairy, and you'll end up crating work-arounds for work-arounds.

Instead, create a single event listener.

// Listen for clicks on the entire window
document.addEventListener('click', function (event) {

// If the clicked element has the `.click-me` class, it's a match!
if (event.target.matches('.click-me')) {
// Do something...
}

});

The method above is an example. It's pretty heavy-handed as it's looking at the whole page. But you can scope it to just the section you want.

via Listening for events on multiple elements using JavaScript event delegation


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.