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.

Event.stopPropation();

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

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

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) => {
    e.stopPropagation();
    
    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.