20 min25 XP

Event Bubbling

Understanding Event Propagation

Step 1 of 5

What is Event Bubbling?

Event bubbling is when an event starts at the element you clicked and then "bubbles up" to all its parent elements, triggering their event listeners too!

Think of Bubbles:

When you click an element, the event is like a bubble that rises up through all the parent elements, one by one, until it reaches the top of the page.

Each parent element with an event listener gets notified as the bubble passes through!

Simple Example

Imagine you have a button inside a div:

<!-- HTML -->
<div class="container">
<button>Click Me</button>
</div>

// JavaScript
const button = document.querySelector('button')
const container = document.querySelector('.container')

button.addEventListener('click', function() {
console.log('Button clicked!')
})

container.addEventListener('click', function() {
console.log('Container clicked!')
})

// When you click the button, BOTH messages appear!
// First: "Button clicked!"
// Then: "Container clicked!" (bubbled up)