Event Bubbling vs Event Capturing in JavaScript
When you click on an element inside nested elements, the event doesnβt just happen on that element β it travels through the DOM. There are two ways this can happen: capturing and bubbling.
1. Event Capturing (trickle down)
- The event starts at the top (
document
) and goes down through each parent until it reaches the target. - Analogy: a grandparent tells a message β parent β child.
2. Event Bubbling (bubble up)
- The event starts at the target element and then goes up through the parents until the root (
document
). - Analogy: bubbles rise from the bottom of a glass to the top.
3. Default in JavaScript
- By default, JavaScript uses bubbling.
- To use capturing, pass
true
as the third parameter inaddEventListener
.
// Bubbling (default)
button.addEventListener("click", () => {
console.log("Button clicked!");
});
// Capturing
div.addEventListener(
"click",
() => {
console.log("DIV clicked during capturing!");
},
true // π capturing enabled
);
4. Event Flow Order
When you click the button:
- Capturing phase: document β body β div β button
- Target phase: the button itself
- Bubbling phase: button β div β body β document
5. Why does this matter?
- Capturing: less common, useful if you want to intercept early.
- Bubbling: very common, great for event delegation (attach one listener to a parent instead of every child).
π§ Quick Mental Model
- Capturing = trickle down (parent β child)
- Bubbling = bubble up (child β parent)
β‘ Thatβs it! Now you know how events travel in JavaScript.