Event bubbling and stopPropagation in JavaScript
Intermediate · 4 min read
Click a button inside a card inside a page, and you haven't only clicked the button. You've clicked the card and the page too. Browsers deliver the click to each of them in turn, from the inside out. Understanding that journey explains a lot of puzzling bugs, like a menu that closes the moment it opens.
In this tutorial you will nest three elements, watch a click travel up through them, then stop it partway with stopPropagation, and see the one thing stopPropagation does not stop. You should have used addEventListener.
Bubbling
When an event happens on an element, the browser first runs the listeners on that element. Then it moves to the element's parent and runs its listeners, then the grandparent's, and so on up to the top of the page. Like a bubble rising through water, the event floats upward. That's why it's called bubbling.
Here are the nested elements:
<div id="grandparent">
grandparent
<div id="parent">
parent
<button id="child" type="button">child</button>
</div>
</div>
Two ways to stop it
event.stopPropagation()stops the event moving on to the next element up.event.stopImmediatePropagation()does that and also skips any other listeners still waiting on the current element.
The difference only shows when one element has more than one listener, which is exactly what we'll set up.
Here is the exercise. Try it yourself first, or read on and we will build it.
13 Bubbling, and stopping it
fairShow an event travelling up through nested elements, then stop it partway with stopPropagation.
Stuck? Three hints, smallest first
- 1. A click on the innermost element runs the handlers of every ancestor, innermost first.
- 2.
stopPropagation()stops the travel but still runs the other handlers on the same element. - 3.
stopImmediatePropagation()stops those too.
Step 1: watch it bubble
const child = document.getElementById('child');
const parent = document.getElementById('parent');
const grandparent = document.getElementById('grandparent');
let log = [];
child.addEventListener('click', () => log.push('child'));
parent.addEventListener('click', () => log.push('parent'));
grandparent.addEventListener('click', () => log.push('grandparent'));
document.body.addEventListener('click', () => log.push('body'));
child.dispatchEvent(new Event('click', { bubbles: true }));
console.log(log); // ['child', 'parent', 'grandparent', 'body']
One click on the child ran four listeners, innermost first. bubbles: true makes our pretend click bubble like a real one. Without it, only the child's listener would run.
Step 2: stop it at the parent
Now give the parent two listeners. The first one calls stopPropagation():
const child = document.getElementById('child');
const parent = document.getElementById('parent');
const grandparent = document.getElementById('grandparent');
let log = [];
child.addEventListener('click', () => log.push('child'));
parent.addEventListener('click', (event) => {
log.push('parent');
event.stopPropagation();
});
parent.addEventListener('click', () => log.push('parent, second listener'));
grandparent.addEventListener('click', () => log.push('grandparent'));
document.body.addEventListener('click', () => log.push('body'));
child.dispatchEvent(new Event('click', { bubbles: true }));
console.log(log); // ['child', 'parent', 'parent, second listener']
The grandparent and the body never heard the click. But look at the third entry: the parent's second listener still ran. stopPropagation() stops the event leaving the current element. Everything else on that element still gets its turn.
Step 3: stop everything at once
const wrap = document.createElement('div');
const hard = document.createElement('button');
wrap.appendChild(hard);
document.body.appendChild(wrap);
const log = [];
hard.addEventListener('click', (event) => {
log.push('first');
event.stopImmediatePropagation();
});
hard.addEventListener('click', () => log.push('second'));
wrap.addEventListener('click', () => log.push('wrapper'));
hard.dispatchEvent(new Event('click', { bubbles: true }));
console.log(log); // ['first']
stopImmediatePropagation() stops the second listener on the same button and the wrapper above it. Listeners on one element run in the order they were added, so "first" ran before it could stop anything.
Step 4: stopping isn't preventing
stopPropagation() is easy to confuse with preventDefault(), but they do different jobs:
const event = new Event('click', { bubbles: true, cancelable: true });
event.stopPropagation();
console.log(event.defaultPrevented); // false
stopPropagation controls where the event travels. preventDefault cancels the browser's own reaction, such as following a link or ticking a checkbox. Stopping propagation on a checkbox's click doesn't stop it ticking.
Step 5: target and currentTarget
As the click travels, two properties on the event tell you where you are:
const child = document.getElementById('child');
const grandparent = document.getElementById('grandparent');
grandparent.addEventListener('click', (event) => {
console.log(event.target.id, event.currentTarget.id); // child grandparent
});
child.dispatchEvent(new Event('click', { bubbles: true }));
event.target stays the element that was clicked, all the way up. event.currentTarget is the element whose listener is running now.
A word of caution
It's tempting to sprinkle stopPropagation() around to stop "extra" handlers firing. Be careful. A listener higher up the page may depend on seeing every click: a menu that closes on outside clicks, analytics, or an event delegation listener added later by someone else. Stopping propagation silently breaks all of them. Use it where you need it, like a dropdown's own button, not as a habit.
The full solution
The panel builds the three nested elements plus the body listener, and clicks the child with and without the stop at the parent. Its checks confirm all five handlers run innermost first, stopPropagation keeps the event from the grandparent and the body but still runs the parent's second listener, stopImmediatePropagation stops that too, stopping is not preventing the default, and target stays the same while currentTarget changes. Press Run, then tick the checkbox in the live demo and click the child.
allow-scripts only, so it cannot reach this page.const child = el('button', { id: 'child', type: 'button' }, 'child');
const parent = el('div', { id: 'parent' }, ['parent', child]);
const grandparent = el('div', { id: 'grandparent' }, ['grandparent', parent]);
document.body.appendChild(grandparent);
let log = [];
let stopAtParent = false;
child.addEventListener('click', () => log.push('child'));
parent.addEventListener('click', (event) => {
log.push('parent');
if (stopAtParent) event.stopPropagation();
});
parent.addEventListener('click', () => log.push('parent, second listener'));
grandparent.addEventListener('click', () => log.push('grandparent'));
document.body.addEventListener('click', () => log.push('body'));
const clickChild = () => { log = []; fire(child, 'click'); return log; };
console.log('bubbling all the way :', clickChild());
stopAtParent = true;
const stopped = clickChild();
console.log('stopped at the parent:', stopped);
console.log('<- note the second listener on the parent STILL ran');
// stopImmediatePropagation also stops the siblings on the same element.
stopAtParent = false;
const immediateLog = [];
const hard = el('button', { type: 'button' }, 'hard stop');
const hardWrap = el('div', {}, hard);
document.body.appendChild(hardWrap);
hard.addEventListener('click', (e) => { immediateLog.push('first'); e.stopImmediatePropagation(); });
hard.addEventListener('click', () => immediateLog.push('second'));
hardWrap.addEventListener('click', () => immediateLog.push('wrapper'));
fire(hard, 'click');
// Snapshotted now: later assertions fire more clicks, and this claim is about
// this one click.
const immediate = [...immediateLog];
console.log('stopImmediatePropagation:', immediate, '<- the second listener never ran');
Output
13 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 13 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a click on the child runs every ancestor handler', clickChild(), ['child', 'parent', 'parent, second listener', 'grandparent', 'body']);
test('innermost first', clickChild()[0], 'child');
test('outermost last', clickChild().at(-1), 'body');
test('stopPropagation stops it travelling further out', stopped.includes('grandparent'), false);
test('and the body never hears it', stopped.includes('body'), false);
test('but the child and parent did run', stopped.slice(0, 2), ['child', 'parent']);
test('and the parent\u2019s OTHER listener still ran', stopped.includes('parent, second listener'), true);
test('which is exactly what stopImmediatePropagation prevents', immediate, ['first']);
test('the second listener on that element never ran', immediate.includes('second'), false);
test('nor did the wrapping element', immediate.includes('wrapper'), false);
test('stopping propagation is not preventing the default', (() => { const e = new Event('click', { bubbles: true, cancelable: true }); e.stopPropagation(); return e.defaultPrevented; })(), false);
test('target stays the element that was clicked throughout', (() => { let targets = []; const fn = (e) => targets.push(e.target === child); grandparent.addEventListener('click', fn); fire(child, 'click'); grandparent.removeEventListener('click', fn); return targets; })(), [true]);
test('while currentTarget changes per handler', (() => { let seen = null; const fn = (e) => { seen = e.currentTarget === grandparent; }; grandparent.addEventListener('click', fn); fire(child, 'click'); grandparent.removeEventListener('click', fn); return seen; })(), true);
Bubbling runs handlers from the clicked element outwards to the document. The assertion listing all five in order is the whole mental model.
The distinction people miss: stopPropagation() stops the event moving to the next element, but every other listener on the current element still runs — the assertion shows the parent's second listener firing after the first called stopPropagation. stopImmediatePropagation() is the one that stops those as well.
And stopping propagation is not the same as preventDefault(). One controls where the event travels; the other cancels the browser's built-in reaction. A checkbox whose click handler calls only stopPropagation still ticks. Reaching for stopPropagation as a general habit is worth avoiding: it silently breaks any delegated listener higher up, including ones added later by code you did not write.
Common mistakes
- Expecting
stopPropagation()to silence the same element. Other listeners on that element still run. UsestopImmediatePropagation()for that. - Using
stopPropagation()to cancel a default action. It doesn't. A link still navigates. UsepreventDefault(). - Stopping propagation everywhere. It breaks listeners further up the page, including delegated ones you didn't write.
Try it yourself
- Log
event.currentTarget.idin every listener instead of a fixed name, and check the order matches Step 1. - Dispatch the click with
{ bubbles: false }. Which listeners run now? - Add a checkbox. When it's ticked, the parent's listener calls
stopPropagation(); when it isn't, the click bubbles all the way.