Event bubbling is a fundamental concept in JavaScript that describes how events propagate through the Document Object Model (DOM) tree. When an event occurs on an element, it doesn’t just affect that element — it can also trigger events on its parent elements, and so on, all the way up to the root of the DOM tree.
To understand event bubbling, let’s consider a simple HTML structure:
<div id="outer">
<div id="inner">
<button id="myButton">Click me</button>
</div>
</div>
In this example, we have an outer <div>
, an inner <div>
, and a <button>
element inside the inner <div>
.
Now, let’s say we add a click event listener to the button:
const button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
console.log('Button clicked!');
});
When you click the button, the 'click'
event is triggered on the button element. But that's not the end of the story - the event doesn't just stop there. Instead, it "bubbles" up through the DOM tree, triggering the same event on the parent elements.
So, in this case, the 'click'
event will also be triggered on the inner <div>
and the outer…