JavaScriptDOM and events

Event.preventDefault()

Blocks the browser’s default action for an event, for example submitting a form or following a link’s address.

Returns
undefined
On this page

Example

#
JavaScript
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()
Console
Sending with fetch: emma@example.com
The page won’t reload: true

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

#
Syntax
event.preventDefault()

More examples

#
A link handled by JavaScript
JavaScript
const more = document.querySelector('#more')

more.addEventListener('click', (event) => {
  event.preventDefault()
  console.log('Loading more courses without navigating to another page')
})

more.click()
Console
Loading more courses without navigating to another page
A blocked checkbox
JavaScript
const terms = document.querySelector('#terms')

terms.addEventListener('click', (event) => {
  event.preventDefault()
  console.log('Read the terms first')
})

terms.click()
console.log(terms.checked)
Console
Read the terms first
false

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(), not preventDefault().

Related entries

#

Spotted a mistake or missing an example? Write to us.