How to Stop Event Propagation in JavaScript?

In JavaScript, you can prevent an event from propagating by calling either of the following two methods on the event object:

  1. Event.stopPropagation() — stops event propagation to other elements in the event flow, either in the capturing or bubbling phase, but allows other event listeners attached to the same element to be executed;
  2. Event.stopImmediatePropagation() — stops event propagation to other elements in the event flow, either in the capturing or bubbling phase, and prevents other event listeners attached to the same element from being executed.

In an inline event handler, such as one specified by the onclick attribute on an HTML element, you can also return false to stop propagation and prevent default behavior of the element.

For example:

<div id="grandparent">
  <div id="parent">
    <button id="child">Click me</button>
  </div>
</div>
document.getElementById('grandparent').addEventListener('click', function() {
  console.log('Grandparent clicked');
});

document.getElementById('parent').addEventListener('click', function(event) {
  event.stopPropagation();
  console.log('Parent clicked');
});

document.getElementById('child').addEventListener('click', function() {
  console.log('Child clicked');
});

If you click the button in this example, the following output will be logged in the console:

Child clicked
Parent clicked

In this example, clicking on the button will stop propagation of the event beyond the parent element as it has event.stopPropagation() specified in the event handler. This will only prevent the event from bubbling up the hierarchy of elements in the document. Other event listeners on the same element will still be triggered. If you want to prevent all event listeners on an element from being triggered, then you can use the Event.stopImmediatePropagation() method instead.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.