Event Bubbling and Capturing (JavaScript)
Table of contents
Bubbling
Event bubbling is a mechanism in which an event triggered on a specific element propagates through its parent elements in the DOM hierarchy, triggering their respective event handlers.
So, here is an example of bubbling:
How to stop bubbling?
A bubbling event goes from the target element straight up. Normally it goes upwards till <html>
, and then to document
object, and some events even reach window
, calling all handlers on the path.
But any handler may decide that the event has been fully processed and stop the bubbling. The method for it is event.stopPropagation()
.
Capturing
Capturing refers to the phase in which an event is first propagated from the outermost ancestor element towards the target element during event propagation. During this phase, event handlers attached to the ancestor elements are executed before the event reaches the target. It allows capturing the event's occurrence and performing actions or modifications at higher levels of the DOM hierarchy before reaching the actual target element.
The standard DOM Events describes 3 phases of event propagation:
Capturing phase – the event goes down to the element.
Target phase – the event reached the target element.
Bubbling phase – the event bubbles up from the element.
We often forget about the capturing phase because it's rarely used.
To catch an event on the capturing phase, we need to set the handler capture
option to true
:
elem.addEventListener(..., {capture: true})
// or, just "true" is an alias to {capture: true}
elem.addEventListener(..., true)
Subscribe to my newsletter
Read articles from Devashish Jadhav directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by