Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Events

Event.preventDefault() method

Reference for Event.preventDefault(): stop links, forms, keys and other default browser actions, learn which events are cancelable and when it has no effect.

Many events come with a default action that the browser performs after your listeners have run: following a link, submitting a form, typing a character, opening a context menu, scrolling on a wheel turn. Calling event.preventDefault() inside a listener tells the browser not to do that.

It cancels only the default action. The event keeps travelling to other listeners and up through ancestors, unless you also stop propagation. The effect only works when the event is cancelable (event.cancelable is true).

JavaScript
link.addEventListener("click", (event) => {
  event.preventDefault();
});

Try it

A link and a form that do not navigate
Filtering typed characters

Syntax

JavaScript
event.preventDefault()

Parameters

None.

Return value

undefined. Afterwards event.defaultPrevented is true if the event was cancelable.

Usage notes

  • Check event.cancelable. Events such as scroll, load, focus and blur are not cancelable. Calling preventDefault() on them does nothing.
  • Passive listeners ignore it. If a listener was added with { passive: true }, a call to preventDefault() is ignored and the console shows a warning. Wheel and touch listeners on window, document and body are passive by default.
  • Call it synchronously. The browser decides what to do right after the listeners return. Calling preventDefault() later, inside setTimeout() or after an await, is too late.
  • It does not stop propagation. Parent listeners still run. Use event.stopPropagation() for that. Returning false from an onclick property handler also cancels the default action but does not stop propagation; prefer the explicit call. Returning false from an addEventListener() listener does nothing.
  • Prefer cancelling the right event. Blocking keydown stops typing, but input events can come from paste, drag and dictation as well. For validation use beforeinput, or check the value in input and correct it.
  • Accessibility. If you cancel a link click to handle it in JavaScript, keep the real href so the link still works without scripting and for middle clicks.
  • Cancelling dispatched events. For events you create yourself with { cancelable: true }, dispatchEvent() returns false when a listener cancelled it.
  • beforeunload and others. A few events use preventDefault() as a signal, for example beforeunload (to request a confirmation prompt), and dragover/dragenter (to allow dropping).

Browser support

preventDefault() works in every browser. The passive-listener behavior for wheel and touch events on the root objects is implemented in all current browsers.