Clicking a link changes page. Submitting a form reloads the page. Those reactions were never written by anyone, they belong to the browser.
When an interface takes over, they have to be switched off, one at a time and at the right moment.
Definition
preventDefault is a method of the event object that cancels the action the browser had planned for this event. It does not interrupt propagation: the following listeners run as usual.
const form = document.querySelector("#signup");
form.addEventListener("submit", (event) => {
event.preventDefault(); // the page does not reload
console.log(new FormData(form).get("email"));
});This is the foundation of any submission handled in JavaScript: the line cancels the reload, the rest of the function sends the data with fetch() and refreshes the display.
The actions commonly canceled
| Event | Canceled action |
|---|---|
submit | Sending the form and reloading the page |
click on a link | Navigating to the address of the link |
contextmenu | Opening the context menu |
dragover | The default refusal of a file drop |
keydown | Typing the character into the field |
Not every event can be canceled. The event.cancelable property says so, and a call on an event that cannot be canceled does nothing whatsoever.
The passive listener trap
To keep scrolling smooth, browsers treat touchstart, touchmove and wheel as passive by default when the listener sits on window, document or the body of the page. The cancellation is then ignored, with a warning in the console.
document.addEventListener("wheel", (event) => {
event.preventDefault(); // effective thanks to the option below
}, { passive: false });Blocking the scroll of a page degrades the experience and sometimes accessibility. Before writing that call, check whether a CSS property such as overscroll-behavior already answers the need.
Knowing whether the action was canceled
The event.defaultPrevented property hands back true as soon as a listener has called the method. A listener placed higher up can therefore notice that another one already took over, and stand back.
Frequently asked questions
How does it differ from stopPropagation?
The two methods touch different machinery. preventDefault cancels what the browser was about to do, without changing the path of the event. stopPropagation stops that path, without preventing the default action. The topic is covered in Event propagation.
Why does the page reload despite the call?
Three causes cover nearly every case: an error thrown before the line, which interrupts the function, a listener placed on the button instead of the form, or a click event listened to where submit was expected. The console settles it in seconds.
Is return false enough?
Only inside an HTML attribute such as onsubmit, a spelling best left behind. Inside a function handed to addEventListener(), the return value is ignored: the return leaves the function and nothing more.