When you click on a DOM element with an event listener, the browser first performs top-down event capture, and then, when it has captured the final target, it starts bubbling bottom-up.
Source: Event Bubbling and Capturing in JavaScript - javatpoint
However, event capturing is set to false by default, which means that event listeners would only return a callback during the bubbling phase. Unless you set the third parameter of addEventListener
to true
.
element.addEventListener('click', function(event) {
console.log('Event handler executed during capturing phase');
}, true);
If you want to stop bubbling at the child element, you can use event.stopPropagation()
in the listener that listens to that child.
document.getElementById('child').addEventListener('click', function(event) {
// Perform some action for the child element
console.log('Child element clicked');
// Stop the event from bubbling up to parent elements
event.stopPropagation();
});
document.getElementById('parent').addEventListener('click', function(event) {
// This will not be executed if the event.stopPropagation() is called
console.log('Parent element clicked');
});
References