sajad torkamani

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 for buttonEl first
  • Followed by handleClick for sectionEl
  • Followed by handleClick for mainEl

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.

Sources / related

Tagged: JavaScript