Member-only story
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!');
});