What is the difference between bubbling and capturing?
In JavaScript, when an event (like a click) happens on an element, it doesnβt just stay on that element. Instead, it travels through the DOM in two main phases: capturing and bubbling.
1. Event Capturing (Trickling down)
- The event starts from the window β document β
<html>β<body>β¦ down to the target element. - Itβs also called the capture phase.
- At this stage, parent elements get a chance to βcatchβ the event before it reaches the target element.
- To use capturing, you pass
trueas the third argument inaddEventListener:parent.addEventListener("click", handler, true);
2. Event Bubbling (Bubbling up)
- After the event reaches the target element, it bubbles back up from the target β parent β ancestor elements β up to the document and window.
- This is the default phase when you add an event listener without specifying the third argument.
child.addEventListener("click", handler); // bubbling by default
Visual Flow
Capturing Phase: Window β Document β HTML β Body β Parent β Child (Target)
Target Phase: Event executes on the target element
Bubbling Phase: Child (Target) β Parent β Body β HTML β Document β Window
Example
<div id="parent">
<button id="child">Click Me</button>
</div>
document.getElementById("parent").addEventListener("click",
() => console.log("Parent clicked (capturing)"),
true // capturing
);
document.getElementById("parent").addEventListener("click",
() => console.log("Parent clicked (bubbling)"),
false // bubbling
);
document.getElementById("child").addEventListener("click",
() => console.log("Child clicked"),
false
);
If you click the child button, the console order will be:
Parent clicked (capturing) // captured on the way down
Child clicked // target
Parent clicked (bubbling) // bubbled on the way up
β Summary:
- Capturing: Event travels top β down (before the target).
- Bubbling: Event travels bottom β up (after the target).
- Default is bubbling in most cases.
No comments yet! You be the first to comment.
