Bubbling means that:

  • When an event happens on an element, it first runs the handler directly on it. Then it is moved to the parent, and it goes up to the end of the ancestors, just like bubbles in water.
<form>
  <input id="name" type="text">
  <input id="surname" type="text">
  <div>
    <p id="clicker" >Click me please!</p>
  </div>
</form>

Thanks to that we can, for example, have an event listener on a <form> and listen on all child events in one global handler.

How to stop it?

The solution for it is event.stopPropagation(). I It will stop event propagation but only on the current handler. That means when you have multiple handlers for an event, you will stop only current one

  • Use it when absolutely necessary - it may be really hard for debugging/refactoring in the future.
  • When you think you may need it - go for custom events!

Capturing - the inverse of bubbling

addEventListener(..., true) can take up the third parameter - which inverses the way of event journey. I.e. the event will propagate down in ancestors hierarchy.

Examples

  • Bubbling and capturing - see it in action. Click elements to see how event propagates

See the Pen #Bubbling by Karol Świeca (@khazarr) on CodePen.


  • Propagation stopped - in this example the listener on level-four has an event.stopPropagation inside - when bubbling path is drawn. See what it changes

See the Pen #Bubbling - stop propagation by Karol Świeca (@khazarr) on CodePen.


Karol Świeca

My thougths on JavaScript, AWS Cloud and other aspects of being Software Engineer