preventDefault
Learn to prevent an event's default behavior (e.g. form submit).
preventDefault
Some events have a default behavior that the browser carries out. Clicking a link navigates the page, submitting a form reloads the page. event.preventDefault() blocks this behavior.
link.addEventListener('click', (event) => {
event.preventDefault();
console.log('prevented');
});The event still bubbles; only the browser's default action is stopped. If you also want to stop propagation, you call stopPropagation separately.
Preventing form submission
For form submission, preventDefault is very useful. Without reloading the page, you can process the data with JavaScript, run validation and show the result. This is the basis of modern single-page apps.
form.addEventListener('submit', (event) => {
event.preventDefault();
console.log('form processed');
});The submit event is added to the form, not the button. This way the submission is also caught when pressing Enter. If validation fails, you stop the submission with preventDefault and show the user a warning.
Exercise Call preventDefault on form submit
Define a form variable and select the #form element. Add a submit listener that calls event.preventDefault() to stop the page from reloading.
Show example solution
const form = document.querySelector('#form');
form.addEventListener('submit', (event) => {
event.preventDefault();
console.log('form submitted');
});
Test yourself
-
When is event.preventDefault() used?
form.addEventListener('submit', (event) => { event.preventDefault(); });- When creating a new element
- When adding a listener
- When you want to prevent the default behavior
- When you want to stop propagation
Show answer
When you want to prevent the default behavior — Correct! preventDefault is used to prevent the default behavior.
-
Prevent the default behavior
form.addEventListener('submit', (event) => { event.____(); console.log('submitted'); });Show answer
form.addEventListener('submit', (event) => { event.preventDefault(); console.log('submitted'); }); -
Match events to their behaviors
- preventDefault
- Prevents default behavior
- submit
- Form submission
- click (link)
- Page navigation