What is event bubbling?
4 December 2022 (Updated 4 December 2022)
On this page
In a nutshell
Event bubbling is when an event triggered on a nested HTML element bubbles up to trigger the same event for its parent elements.
So if you had HTML like:
<main>
<section>
<button>Click me</button>
</section>
</main>
And some JavaScript like:
const mainEl = document.querySelector('main')
const sectionEl = document.querySelector('section')
const buttonEl = document.querySelector('button')
const outputEl = document.querySelector('#output')
mainEl.addEventListener('click', handleClick)
sectionEl.addEventListener('click', handleClick)
buttonEl.addEventListener('click', handleClick)
function handleClick(event) {
outputEl.innerHTML += `You clicked on a ${event.currentTarget.tagName}<br>`
}
Clicking on the <button>
element will:
- Trigger
handleClick
forbuttonEl
first - Followed by
handleClick
forsectionEl
- Followed by
handleClick
formainEl
We say that the event “bubbles” up from <button>
to its parent elements See CodeSandbox for an example.
You can use the Event.stopPropagation
method to prevent events on a nested element from bubbling up to parent elements. See CodeSandbox for an example of how to do this.
Event bubbling is the default behaviour but you can also use event capturing so that event handlers for the outermost element are invoked first.
Tagged:
JavaScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment