CodeBlanks Logo Icon CodeBlanks

stopPropagation

JavaScript course · Intermediate · Lesson 38/134

Learn to stop an event from bubbling up and when to use it.

stopPropagation

Sometimes you do not want an event to bubble up to the parent. The event.stopPropagation() method stops the event from reaching ancestors. The child listener still runs, but the parent listener is not triggered.

child.addEventListener('click', (event) => {
  event.stopPropagation();
});

Use it only when truly needed; otherwise listeners on ancestor elements will not run and unexpected behavior may appear. It makes sense when the event is only about the target element.

Capture and bubble phases

An event goes through three phases: capture (parent to child), target (at the target element) and bubble (child to parent). By default, listeners run in the bubble phase.

parent.addEventListener('click', handler, true);

If you pass true as the third parameter, the listener runs in the capture phase; the parent fires before the child. Usually the bubble phase is enough.

Exercise Stop propagation in the child listener

Define a child variable and select the #child element. Add a click listener that calls event.stopPropagation() to stop the event from bubbling.

Show example solution
const child = document.querySelector('#child');
child.addEventListener('click', (event) => {
  event.stopPropagation();
  console.log('child');
});

Test yourself

  1. What does event.stopPropagation() do?

    child.addEventListener('click', (event) => {
      event.stopPropagation();
    });
    • Prevents the event's default behavior
    • Removes the listener from the list
    • Triggers the event again
    • Stops the event from bubbling to the parent
    Show answer

    Stops the event from bubbling to the parent — Correct! stopPropagation stops the event from bubbling up.

  2. Stop the propagation

    child.addEventListener('click', (event) => {
      event.____();
    });
    Show answer
    child.addEventListener('click', (event) => {
      event.stopPropagation();
    });
  3. Match phases to their directions

    stopPropagation
    Stops propagation
    Capture phase
    Parent to child
    Bubble phase
    Child to parent

All lessons in Intermediate