How to stop propagation of an event in JavaScript

To prevent an event from further propagation in the capturing and bubbling phases, you can call the Event.stopPropation() method in the event handler.

Propagation of an event means bubbling up to parent elements or capturing down to child elements.


Let us say you have got the following HTML code snippet:

<div id="wrapper">
    <button id="signup">Sign Up</button>

When you click on the button, the event is bubbled up to the <div> element. The following code will display two alerts when you click the button:

const div = document.querySelector('#wrapper');
const btn = document.querySelector('#signup');

// add <div> event handler
div.addEventListener('click', (e) => {
    alert('The wrapper box was clicked!');

// add button event handler
btn.addEventListener('click', (e) => {
    alert('The button was clicked!');

To stop the click event from propagating to the <div> element, you have to call the stopPropagation() method in the event handler of the button:

btn.addEventListener('click', (e) => {
    alert('The button was clicked!');

Note that the Event.stopPropagation() method does not prevent any default behaviors of the element from occurring; for instance, clicks on links and checkboxes checked are still processed. To stop default behaviors, you should use the Event.preventDefault() method.

The Event.stopPropagation() method works in all modern browsers and IE9 and above.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.