Event Propagation: Bubbling and Capturing
- Event Bubbling: This is the most commonly used form of event propagation. When an event bubbles, it starts from the target element (the element that triggered the event) and then moves upwards through the ancestors in the DOM tree. The event goes from the most specific element (innermost) out to the least specific (outermost).
- Event Capturing: This is the opposite of event bubbling. Instead of starting from the target element and moving up, event capturing starts from the top (outermost element) and goes down to the target element.
By default, event handlers are set to use bubbling propagation. If you wish to use event capturing, you need to specify this when you set your event listener, using the third parameter of the
element.addEventListener('click', functionHandler, true); // Use capturing
Here, the ‘true’ signifies that event capturing should be used.
An important method to understand in the context of event propagation is
event.stopPropagation(). This method, when called within an event handler, stops the event from continuing to propagate through the DOM.
This can be useful in many scenarios. For example, if you have a click event on both a child and a parent element and don’t want the parent’s event to fire when the child is clicked, you can call
event.stopPropagation() in the child’s event handler.
// Handle event
The Difference Between event.stopPropagation() and event.preventDefault()
event.stopPropagation() stops the event from propagating further through the DOM,
event.preventDefault() prevents the default action associated with the event from occurring. For example, calling
event.preventDefault() in the click event handler for a link would prevent the link from being followed.
// Handle event