Event. preventDefault()
Blocks the browser’s default action for an event, for example submitting a form or following a link’s address.
- Returns
undefined
Example
#const form = document.querySelector('#login')
form.addEventListener('submit', (event) => {
event.preventDefault()
const data = new FormData(form)
console.log('Sending with fetch:', data.get('email'))
console.log('The page won’t reload:', event.defaultPrevented)
})
form.requestSubmit()The last line submits the form from code, so the result appears right away. Clicking the button in the preview works the same way.
Definition and usage
#Many events have a default browser reaction: clicking a link opens a new address, submitting a form reloads the page, and clicking a checkbox changes its state. Calling event.preventDefault() in a handler function blocks that reaction, so you can handle the situation your own way.
The most common example is a form: you block the page reload, validate the data, and send it with fetch(). The event.defaultPrevented property lets you check whether the default action has already been blocked.
preventDefault() doesn’t stop the event from propagating to parent elements; stopPropagation() is for that. It also won’t work in a handler added with the passive: true option, or for events that can’t be canceled (in that case event.cancelable is false).
Syntax
#event.preventDefault()More examples
#const more = document.querySelector('#more')
more.addEventListener('click', (event) => {
event.preventDefault()
console.log('Loading more courses without navigating to another page')
})
more.click()const terms = document.querySelector('#terms')
terms.addEventListener('click', (event) => {
event.preventDefault()
console.log('Read the terms first')
})
terms.click()
console.log(terms.checked)Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- In a form handler, call
preventDefault()right at the start of the function. If an error happens later, the page still won’t reload. - Don’t block the default action without a reason. Links and buttons should behave the way the user expects, including with keyboard input.
- To stop an event from propagating up to parents, use
stopPropagation(), notpreventDefault().
Related entries
#- EventTarget.addEventListener()Registers a function that’s called every time a given event occurs on an element, for example a click.
- Event.targetThe element on which an event actually occurred, for example the clicked button inside a list.
- FormDataCollects form field values into name-value pairs. The ready-made object can be read or sent to the server with fetch().
- fetch()Sends an HTTP request and returns a promise with the server’s response (a Response object).
- document.querySelector()Returns the first element that matches a CSS selector, or null when nothing matches.
Spotted a mistake or missing an example? Write to us.