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).
link.addEventListener("click", (event) => { event.preventDefault(); });
Try it
Syntax
event.preventDefault()
Parameters
None.
Return value
undefined. Afterwards event.defaultPrevented is true if the event was cancelable.
Usage notes
- Check
event.cancelable. Events such asscroll,load,focusandblurare not cancelable. CallingpreventDefault()on them does nothing. - Passive listeners ignore it. If a listener was added with
{ passive: true }, a call topreventDefault()is ignored and the console shows a warning. Wheel and touch listeners onwindow,documentandbodyare passive by default. - Call it synchronously. The browser decides what to do right after the listeners return. Calling
preventDefault()later, insidesetTimeout()or after anawait, is too late. - It does not stop propagation. Parent listeners still run. Use
event.stopPropagation()for that. Returningfalsefrom anonclickproperty handler also cancels the default action but does not stop propagation; prefer the explicit call. Returningfalsefrom anaddEventListener()listener does nothing. - Prefer cancelling the right event. Blocking
keydownstops typing, butinputevents can come from paste, drag and dictation as well. For validation usebeforeinput, or check the value ininputand correct it. - Accessibility. If you cancel a link click to handle it in JavaScript, keep the real
hrefso the link still works without scripting and for middle clicks. - Cancelling dispatched events. For events you create yourself with
{ cancelable: true },dispatchEvent()returnsfalsewhen a listener cancelled it. beforeunloadand others. A few events usepreventDefault()as a signal, for examplebeforeunload(to request a confirmation prompt), anddragover/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.
Related
Event.stopPropagation()โ stop the event travelling furtherEventTarget.dispatchEvent()โ reports whether an event was cancelled- passive listeners โ when
preventDefault()is ignored - submit event โ cancelling form submission
- Lesson: Events