Event Bubbling (and how to stop it using event.stopPropagation)

Ben Tagtow
2 min readOct 16, 2020

The principle of event bubbling, from javascript.info, states that: When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors. In other words, if you have a div that changes color with a onmouseover event, if you scroll your cursor over any children inside of that div, the onmouseover event will still run.

To illustrate the example in code, if you clicked the innermost <button> in the code snippet below, all three functions (aThirdFunction, anotherFunction, and someFunction) would run:

<div onclick={someFunction}>My div  <p onclick={anotherFunction}> My p tag    <button onclick={aThirdFunction}> My button    </button/>  </p> </div>

So that is event bubbling. It’s a pretty straightforward concept, and it’s certainly a very important tool to be familiar with in Javascript.

However, there are times when you don’t want event bubbling to occur, at least in its default operation. There are plenty of ways to manage this.

event.stopPropagation()

The stopPropagation function stops bubbling at the element where this function is called. For example, if in the above code snippet I had put event.stopPropagation() on the child button, the event would be considered fully processed, and would not bubble up to the <p> and <div> elements.

One important piece of context that I want to emphasize again is that event bubbling starts at the child element and “bubbles” up. Therefore, when the stopPropagation function is called, any events that would have run *after* the element with the stopPropagation function would not run. The child’s event will still run, but it does not bubble up to the parent.

Another note: Event bubbling is not a bad thing. In fact, you almost always will want to let it run its default behavior. You should only event.stopPropagation() when you really need to. In most cases, you can leave event bubbling as is or just manage it by using things like custom events and event.target.

--

--