Event Bubbling and Event Capturing in JavaScript
How DOM events travel through the page, and how to control them.
You may encounter times when you click a button and a click handler on its parent fires too. Or a handler fires when you didn't expect it to. That's not a bug. It's how DOM events travel through the page, and once you understand it you can use it to your advantage.
When an event happens on an element, it first travels down from the window
to the element (capturing), then back up from the element to the window
(bubbling).
The three phases of an event
An event goes through three phases:
- Capturing phase: the event travels down from
windowthrough each ancestor to the target. - Target phase: the event reaches the element that was actually clicked.
- Bubbling phase: the event travels back up through each ancestor to
window(only for events that bubble).
By default, addEventListener listens during the bubbling phase. That's why
most of the time you only notice bubbling.
Event bubbling
Let's say we have three nested elements:
<div id="outer"><div id="middle"><button id="inner">Click me</button></div></div>
And a click listener on each one:
const elements = document.querySelectorAll("#outer, #middle, #inner")elements.forEach((element) => {element.addEventListener("click", () => {console.log(`Clicked: ${element.id}`)})})// Clicking the button logs:// Clicked: inner// Clicked: middle// Clicked: outer
Clicking the button fires its own handler first, then the event bubbles up and
fires the handlers on middle and outer. Clicking on middle (outside the
button) would log middle then outer.
Event capturing
To listen during the capturing phase, pass { capture: true } as the third
argument. (You'll also see the shorthand true.)
elements.forEach((element) => {element.addEventListener("click",() => {console.log(`Captured: ${element.id}`)},{ capture: true })})// Clicking the button now logs:// Captured: outer// Captured: middle// Captured: inner
Capture listeners run from the outside in. If you have both capture and bubble listeners, all of the capture ones run first, then the bubble ones. Capturing is less common, but it's useful when a parent needs to see an event before its children do.
Note: When removing a capture listener, pass { capture: true } to
removeEventListener too, otherwise it won't be removed.
event.target vs event.currentTarget
Inside a handler, the event object tells you two different things:
event.targetis the element where the event started (what was clicked).event.currentTargetis the element the listener is attached to.
const outer = document.querySelector("#outer")outer.addEventListener("click", (event) => {console.log(event.target.id) // innerconsole.log(event.currentTarget.id) // outer})
When you click the button, target is the button but currentTarget is
outer, because that's where the handler lives. With a regular function as the
handler, this is also the currentTarget. More on that in
What is "this" in JavaScript?.
Stopping propagation
Sometimes you don't want an event to keep traveling. Calling
event.stopPropagation() stops it from reaching any more elements.
const inner = document.querySelector("#inner")inner.addEventListener("click", (event) => {event.stopPropagation()console.log("Only the button handles this click")})
Now clicking the button won't fire the handlers on middle or outer. If you
also need to stop other listeners on the same element, use
event.stopImmediatePropagation().
Use this sparingly. Other code, like analytics or a "click outside to close"
menu, often relies on events bubbling up to the document. Stopping
propagation can quietly break it.
Note: stopPropagation() is not the same as preventDefault(). The first
stops the event from traveling, the second stops the browser's default action,
like following a link or submitting a form.
Events that don't bubble
Not every event bubbles. A few common ones that don't are focus, blur,
mouseenter, mouseleave and load. You can check with event.bubbles.
If you need to listen for focus changes on a parent, use focusin and
focusout. They work the same as focus and blur but they bubble:
const form = document.querySelector("form")form.addEventListener("focusin", (event) => {event.target.classList.add("is-focused")})form.addEventListener("focusout", (event) => {event.target.classList.remove("is-focused")})
Every input inside the form is handled by just two listeners on the form.
Leading into event delegation
That last example is the real payoff of bubbling. Instead of adding a listener
to every child, you add one listener to a parent and check event.target to
see which child triggered it. This is called event delegation, and it works for
elements that get added to the page later too.
document.querySelector("ul").addEventListener("click", (event) => {if (event.target.matches("li")) {event.target.classList.toggle("done")}})
One listener handles every list item, no matter how many there are.
Have some feedback on this post? .