Many events have a default action built into the browser:
- clicking a link follows it,
- submitting a form reloads the page or sends data,
- pressing Space scrolls the page,
- right-clicking opens the context menu.
event.preventDefault() cancels that default action. The event itself still happens.
Stopping a link
<a id="link" href="https://example.com">Go to example.com</a>
<p id="out"></p>
<script>
document.querySelector("#link").addEventListener("click", event => {
event.preventDefault();
document.querySelector("#out").textContent = "Link click handled by JavaScript, no navigation.";
});
</script>
Stopping a form submit
The most common use. Without preventDefault, the form submits and the page reloads, and your JavaScript has no chance to run.
<form id="form">
<input id="name" placeholder="Name" required>
<button>Send</button>
</form>
<p id="out"></p>
<script>
document.querySelector("#form").addEventListener("submit", event => {
event.preventDefault();
document.querySelector("#out").textContent = "Hello, " + event.target.elements.name.value;
});
</script>
Always listen for submit on the form, not for click on the button. That way the Enter key works too.
preventDefault is not a magic stop
- It does not stop other listeners, and it does not stop bubbling.
- Some events cannot be cancelled (check
event.cancelable). - For
passivelisteners (scroll, touch), calling it is ignored.
stopPropagation
event.stopPropagation() stops the event from bubbling up to the parent elements. See Event Bubbling.
<div id="outer" style="padding:10px;background:#eee">
Outer <button id="inner">Inner</button>
</div>
<script>
document.querySelector("#outer").addEventListener("click", () => console.log("outer clicked"));
document.querySelector("#inner").addEventListener("click", event => {
event.stopPropagation();
console.log("inner clicked only");
});
</script>
Click the button: only “inner clicked only” appears.
Use sparingly
Stopping propagation can break other code that relies on seeing the event (analytics, closing menus when you click elsewhere). Try to solve the problem without it first.
Two different things
preventDefault = “don’t do the browser’s built-in thing”. stopPropagation = “don’t tell the parents”. They are independent, and you often need only one.