Member-only story

Exploring Event Bubbling and Capturing in JavaScript: Real-World Examples

Understand how events propagate through the DOM and learn to control event flow in your applications

Max N
2 min readApr 10, 2024
Photo by Richard on Unsplash

Event handling is a fundamental concept in JavaScript, and two key mechanisms that govern how events behave are event bubbling and event capturing. In this article, we’ll dive into real-world examples to help you grasp these concepts and how to leverage them in your web development projects.

Event Bubbling

Event bubbling is the default behavior where an event triggered on a specific element will also trigger the same event on its parent elements, all the way up the DOM tree. Let’s look at an example:

<div id="outer">
<div id="inner">
<button>Click me</button>
</div>
</div>
const outer = document.getElementById('outer');
const inner = document.getElementById('inner');
const button = document.querySelector('button');

button.addEventListener('click', (e) => {
console.log('Button clicked!');
});

inner.addEventListener('click', (e) => {
console.log('Inner div clicked!');
});

outer.addEventListener('click', (e) => {
console.log('Outer div clicked!');
});

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet