How to Stop Propagation of an Event in JavaScript
Table of Contents
On the web, events are propagated up to the DOM tree.
This means that if you click on a button, it will also trigger the click event on the button's parent, and so on.
This is usually something that you want, however, sometimes you do not want this event to propagate up to the parent elements.
In this post, we'll learn how to prevent the event from propagating up using JavaScript.
How to prevent the propagation of an event
The recommended way to stop the propagation of an event is to use the the stopPropagation()
method.
This method exists on every event and once called, it will prevent the event from propagating up the DOM tree.
Let's look at an example of a simple click listener:
JAVASCRIPTconst button = document.querySelector("button");
button.addEventListener("click", event => {
console.log("Clicked!");
});
When you click this button, it will fire the event and bubble it up to the top.
At the same time, it will also log the message Clicked!
to the console.
Now let's use stopPropagation()
to prevent the event from bubbling up:
JAVASCRIPTconst button = document.querySelector("button");
button.addEventListener("click", event => {
event.stopPropagation();
console.log("Clicked!");
});
When you click this button, it will not propagate the event up but it will still log the message Clicked!
to the console.
Keep in mind that stopPropagation
is not the same as preventDefault
which will prevent the default action of the event.
If you want to stop the default behavior, use the preventDefault
method instead.
Conclusion
In this post, we learned how to stop the propagation of an event using JavaScript.
Simply call the stopPropagation
method on the event object to stop the event from bubbling up the DOM tree.
Thanks for reading and happy coding!
- Getting Started with Solid
- Getting Started with Svelte
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- Getting Started with Deno
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue