Attaching event listeners to elements that don’t exist yet
Sometimes you need to attach event listeners to elements that don't exist when the page initially loads. This is common in scenarios…
Event bubbling is a concept that describes how events propagate or "bubble up" through the DOM tree. When an event occurs on a nested element in the HTML document, it triggers the event handler on that element, then on its parent, and continues up the hierarchy to the root of the document.
document object and finally to the window object.Consider this HTML structure:
<div id="outer">
<div id="inner">
<button id="button">Click me</button>
</div>
</div>
If you click the button, the event bubbling sequence would be:
button#inner div#outer divbodyhtmldocumentwindowHere's a JavaScript example demonstrating event bubbling:
document.getElementById('button').addEventListener('click', function(e) {
console.log('Button clicked');
});
document.getElementById('inner').addEventListener('click', function(e) {
console.log('Inner div clicked');
});
document.getElementById('outer').addEventListener('click', function(e) {
console.log('Outer div clicked');
});
document.body.addEventListener('click', function(e) {
console.log('Body clicked');
});
If you click the button, you'll see this output in the console:
Button clicked
Inner div clicked
Outer div clicked
Body clicked
Sometimes you might want to prevent an event from bubbling further up the DOM tree. You can do this using the stopPropagation() method:
document.getElementById('button').addEventListener('click', function(e) {
console.log('Button clicked');
e.stopPropagation();
});
Now, if you click the button, only "Button clicked" will be logged, and the event won't bubble up to parent elements.
Event Delegation: Allows you to attach a single event listener to a parent element that will fire for all descendants matching a selector, present and future.
Performance Optimization: Instead of attaching events to multiple elements, you can attach one to a parent, improving performance.
Dynamic Content Handling: Useful for handling events on elements that don't exist at page load but are added dynamically later.
Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.
Take a look at vroni.com