Event bubbling
Learn how an event bubbles up the DOM and what that means.
Event bubbling
When you click an element, the event does not stay on that element alone. It travels up the DOM tree: first the target's listener runs, then its parent's, then the parent's parent. This is called event bubbling.
parent.addEventListener('click', () => console.log('parent'));If you click the child element here, the child's listener fires first, then the parent's. This lets you watch many elements from a single ancestor.
The bubbling order
To see the bubbling order, you add listeners to both the child and the parent. When you click the child, the console logs child first, then parent.
child.addEventListener('click', () => console.log('child'));
parent.addEventListener('click', () => console.log('parent'));The order always starts at the target and moves toward the root. The order in which listeners are added does not matter; the DOM hierarchy does.
Exercise Add listeners for parent and child
Define parent and child variables. Select the #parent and #child elements with querySelector. Add a click listener to each and log a message with console.log.
Show example solution
const parent = document.querySelector('#parent');
const child = document.querySelector('#child');
parent.addEventListener('click', () => { console.log('parent'); });
child.addEventListener('click', () => { console.log('child'); });
Test yourself
-
If you click the child element, in what order do they fire?
parent.addEventListener('click', () => console.log('parent')); child.addEventListener('click', () => console.log('child'));- Only the child listener
- Child first, then parent
- Parent first, then child
- Neither fires
Show answer
Child first, then parent — Correct! The event fires at the target (child) first, then at the parent.
-
Add a click listener for child
const child = document.querySelector('#child'); child.____('click', () => { console.log('clicked'); });Show answer
const child = document.querySelector('#child'); child.addEventListener('click', () => { console.log('clicked'); }); -
Match terms to their meanings
- addEventListener
- Adds an event listener
- event.target
- The event's source element
- Bubbling
- Child to parent propagation