Both methods are used to control event propagation, but they stop events at different levels.
πΉ event.stopPropagation()
What it does
- Stops the event from bubbling up to parent elements
- Does NOT stop other event listeners on the same element
Example
button.addEventListener("click", () => {
console.log("Listener 1");
});
button.addEventListener("click", (e) => {
e.stopPropagation();
console.log("Listener 2");
});
button.addEventListener("click", () => {
console.log("Listener 3");
});
β Output
Listener 1
Listener 2
Listener 3
π§ Explanation
- Event does not reach parent
- All listeners on the same element still run
πΉ event.stopImmediatePropagation()
What it does
- Stops the event from:
- Bubbling to parent elements β
- Executing any remaining listeners on the same element β
Example
button.addEventListener("click", () => {
console.log("Listener 1");
});
button.addEventListener("click", (e) => {
e.stopImmediatePropagation();
console.log("Listener 2");
});
button.addEventListener("click", () => {
console.log("Listener 3");
});
β Output
Listener 1
Listener 2
π§ Explanation
- Event propagation stops completely
- Listener 3 never runs
π₯ Key Differences (Quick Table)
| Feature | stopPropagation | stopImmediatePropagation |
|---|---|---|
| Stops bubbling | β | β |
| Stops capturing | β | β |
| Stops other listeners on same element | β | β |
| Scope | Parent elements only | Same element + parents |
π― When to Use Which?
β Use stopPropagation()
- Prevent parent handlers
- Allow multiple listeners on same element
β Use stopImmediatePropagation()
- Prevent everything else
- Avoid duplicate handlers
- Advanced control scenarios
π― Short Interview Answer
stopPropagation()prevents the event from bubbling to parent elements but allows other listeners on the same element to run.stopImmediatePropagation()stops the event completely, preventing both bubbling and execution of remaining listeners on the same element.
β One-line summary
stopPropagation stops the climb; stopImmediatePropagation stops everything.