TIL event bubbling
POSTED ON:
TAGS: javascript codepen clicks
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: javascript