Javascript
Event Bubbling

Event bubbling

This is a process where when an event is triggered by a DOM element, it will attempt to handle that event if there is a listener attached.

Else, it will bubble up (propagate) to the parent element and check if there is a listener attached.

This process continues until it reaches the document object.

We can use event.stopPropagation() to stop the event from bubbling up.

Good example for interviews

<form onclick="alert('form click event triggered')">
  This is a form element
  <div onclick="alert('div click event triggered')">
    This is a div element
    <p onclick="alert('p click event fires')">This is a p element</p>
  </div>
</form>

Because of event bubbling, the onclick event will be triggered on the p element first, then the div element, and finally the form element.

Here is a detail that needs to be noted. this during bubbling is not necessarily equal to event.target, but equal to event.currentTarget. In other words, thisis the currently executing handler; and event.targetwill always be the one that was actually clicked (in this case the innermost <p>).

event.target and event.currentTarget

  • target is the element that triggered the event (e.g., the user clicked on)
  • currentTarget is the element that the event listener is attached to.