Event: preventDefault() method
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Note: This feature is available inWeb Workers.
ThepreventDefault()
method of theEvent
interface tells theuser agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
The event continues to propagate as usual,unless one of its event listeners callsstopPropagation()
orstopImmediatePropagation()
,either of which terminates propagation at once.
As noted below, callingpreventDefault()
for anon-cancelable event, such as one dispatched viaEventTarget.dispatchEvent()
, without specifyingcancelable: true
has no effect.
If a passive listener callspreventDefault()
, nothing will happen and a console warning may be generated.
Note:Look for better alternatives than usingpreventDefault()
to block default actions. For example, you can use thedisabled
orreadonly
attribute on a form control to prevent it from being interacted with, useHTML constraint validation to reject invalid input, or use theoverflow
property to prevent scrolling.
Syntax
preventDefault()
Parameters
None.
Return value
None (undefined
).
Examples
Blocking default click handling
Toggling a checkbox is the default action of clicking on a checkbox. This exampledemonstrates how to prevent that from happening:
JavaScript
const checkbox = document.querySelector("#id-checkbox");checkbox.addEventListener("click", checkboxClick, false);function checkboxClick(event) { const warn = "preventDefault() won't let you check this!\n"; document.getElementById("output-box").innerText += warn; event.preventDefault();}
HTML
<p>Please click on the checkbox control.</p><form> <label for="id-checkbox">Checkbox:</label> <input type="checkbox" /></form><div></div>
Result
Notes
CallingpreventDefault()
during any stage of event flow cancels the event,meaning that any default action normally taken by the implementation as a result of theevent will not occur.
You can useEvent.cancelable
to check if the event is cancelable.CallingpreventDefault()
for a non-cancelable event has no effect.
Specifications
Specification |
---|
DOM # ref-for-dom-event-preventdefault③ |