Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent event bubbling in a JavaScript event listener?
Asked on Feb 26, 2026
Answer
To prevent event bubbling in JavaScript, you can use the "stopPropagation" method within your event listener. This method stops the event from propagating up the DOM tree.
<!-- BEGIN COPY / PASTE -->
document.getElementById("myButton").addEventListener("click", function(event) {
event.stopPropagation();
console.log("Button clicked, event propagation stopped.");
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- In this example, when the button with the ID "myButton" is clicked, the event listener stops the event from bubbling up to parent elements.
- "stopPropagation" is useful when you want to handle an event at a specific level and prevent it from triggering handlers on ancestor elements.
- Always ensure that "stopPropagation" is called on the event object passed to the event listener.
Recommended Links:
