What is event bubbling and capturing?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Event bubbling and capturing are two phases of event propagation in the HTML DOM API when an event occurs in an element inside another element, and both elements have registered a handle for that event. Understanding how event propagation works is crucial for effective event handling in complex web applications.
Understanding the Event Propagation Model
When an event occurs, it can be propagated through the DOM tree in two ways: from the parent to the child (capturing phase) and from the child to the parent (bubbling phase). This model ensures that an event can be handled at different levels in the DOM hierarchy.
1. Event Capturing (Trickling)
During the capture phase, the event is first captured by the outermost element and propagated to the inner elements. Event capturing is the first phase of the event propagation model.
For example, suppose there is a structure like this:
If a click event is triggered on #btn1, and all elements have event listeners set up for capturing, the event will be captured in the order of #div1, then #div2, and finally #btn1.
2. Event Bubbling
Contrarily to capturing, event bubbling occurs after the event has reached its target. The event bubbles up from the innermost element to the outer elements.
Taking the same HTML structure, if all the handlers are set in the bubbling phase, when the button #btn1 is clicked, the event handling starts at #btn1, bubbles up to #div2, and then finally to #div1.
Event Handlers in JavaScript
In JavaScript, you can add event listeners to elements and specify whether you should catch the event during the capturing or the bubbling phase. The syntax for adding an event listener is as follows:
event– The type of event (e.g., "click", "mouseover").function– The function to run when the event occurs.useCapture– A Boolean value:true– The event handler is set for the capturing phase.false(default) – The event handler is set for the bubbling phase.
Practical Example
Here’s a practical example illustrating both phases:
In this example, clicking on #btn1 will alert 'DIV 1 captured' due to capturing and then 'Button Clicked' due to bubbling.
Summary Table
Here's a summary of the key points for quick reference:
| Phase | Direction | useCapture Value |
| Capturing | Outer to Inner | true |
| Bubbling | Inner to Outer | false |
Final Thoughts
Developers must understand event bubbling and capturing to manage complex event handling scenarios in web applications effectively. By correctly using the propagation model, one can trap events at required levels in the DOM tree, stop unnecessary propagation, and enhance the user interaction and performance of web pages.

