Firefox Tomorrow

web api instance method

Event: preventDefault() method

View on MDN ↗

Available in workers

The preventDefault() method of the Event interface tells the user agent that the event is being explicitly handled, so its default action, such as page scrolling, link navigation, or pasting text, should not be taken.

The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

As noted below, calling preventDefault() for a non-cancelable event, such as one dispatched via dispatchEvent(), without specifying cancelable: true has no effect.

If a passive listener calls preventDefault(), nothing will happen and a console warning may be generated.

[!NOTE] Look for better alternatives than using preventDefault() to block default actions. For example, you can use the disabled or readonly attribute on a form control to prevent it from being interacted with, use HTML constraint validation to reject invalid input, or use the overflow 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 example demonstrates how to prevent that from happening:

JavaScript

const checkbox = document.querySelector("#id-checkbox");

checkbox.addEventListener("click", checkboxClick);

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" id="id-checkbox" />
</form>

<div id="output-box"></div>

Result

Interactive exampleOpen the canonical MDN source to run this embedded demo.

Notes

Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

You can use cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.

Specifications

SpecificationsStandards references are available on the canonical MDN page.

Browser compatibility

Browser compatibilityCompatibility data is available on the canonical MDN page.