DEV Community

Himanshu Gupta
Himanshu Gupta

Posted on

What is Event propagation, capturing, bubbling ?

Image description
Event propagation refers to the mechanism by which events travel through the Document Object Model (DOM) tree, a hierarchical representation of the HTML elements in a web page. When an event (like a click, mouseover, or keypress) occurs on a specific element, it doesn't just affect that element alone. The event "bubbles up" through the DOM tree, potentially triggering event handlers attached to its parent, grandparent, and all the way up to the document object itself.

Phases of Event Propagation:

Capturing Phase: This phase (optional and less commonly used) starts at the document object and travels down the DOM tree to the target element (the element where the event originated). Event handlers attached during this phase are executed first, but in reverse order of their ancestors (bottom-up).

Target Phase: The event reaches the target element, and the event handler attached directly to that element is executed.

Bubbling Phase: This is the default and most common phase. The event bubbles back up the DOM tree from the target element to the document object. Event handlers attached to parent, grandparent, and so on, are executed in the order they appear in the DOM (top-down).
Example Code:(Bubbling Example)

Example Code:(Capturing Example)

Explanation:

Bubbling: Click on the "Click on me!" text inside the innermost div. You'll see the following output in your browser's console:

-Inner Element Clicked (Bubbling)
-Middle Element Clicked (Bubbling)
-Outer Element Clicked (Bubbling)
This demonstrates the bubbling phase, where the click event first triggers the handler on the target element (inner), then bubbles up to its parent (middle), and finally reaches the outermost element (outer).

Capturing (Uncomment to see the difference): Uncomment the lines with the true argument in the addEventListener methods. Now, clicking on the "Click on me!" text will display the following output:

-Outer Element Clicked (Capturing)
-Middle Element Clicked (Capturing)
-Inner Element Clicked (Capturing)
This shows the capturing phase, where the event starts from the document and travels down the DOM, triggering handlers in the reverse order of their ancestors before reaching the target element and bubbling back up.

Key Points:

By default, event propagation follows the bubbling phase.
The capturing phase is less common but can be useful in specific scenarios.
You can use event.stopPropagation() to prevent an event from bubbling further up the DOM tree after it's been handled by a specific element.
Use event propagation judiciously, as it can add complexity to your code if not handled carefully.

Thank you for keep reading. If you liked the article, please hit the ๐Ÿ‘button; if you want to see more articles follow me๐Ÿ˜˜.

Top comments (0)