The event.preventDefault() method in JavaScript

The preventDefault() method of the Event interface lets you prevent the default action of an event.

Preventing form submission

I’d say this is the most frequent use case for me. If a form has validation errors, you’ll want to stop it from submitting.

Given an HTML form:

<form>

  <div>
    <label for="name">Name</label>
    <input id="name" type="text" name="name">
  </div>

  <div>
    <label for="email">Email</label>
    <input id="email" type="email" name="email">
  </div>

  <div>
    <label for="message">Message</label>
    <textarea id="message" name="message"></textarea>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>

</form>

You can stop it from submitting by listening to the submit event and calling the preventDefault() method:

// Select the form
var form = document.querySelector("form");

// Stop it from submitting
form.addEventListener("submit", function (event) {
  event.preventDefault();
});

Other examples

There are other things you can do, such as:

I won’t get into them, though.

I would generally advise against disabling an element’s default behaviour unless you really need to.

Form validation is the only real use case for me.

The thing to understand is that the preventDefault() method disables the default behaviour of an element.

The event must be cancelable

You can only call the preventDefault() method if an event is cancelable.

There are two ways to find out:

  1. Check the MDN Web Docs
  2. Check the event’s cancelable property

The MDN Web Docs

Let’s say I want to find out if the submit event is cancelable. I would go to my search engine and look for “mdn submit event”. This takes me to the page for the submit event. At the top of the page, I can see that the event is indeed cancelable:

A screenshot from the MDN Web Docs showing that the submit event is cancelable.

The cancelable property

The other way is to check the event’s cancelable property. It will be true or false depending on the event in question:

var form = document.querySelector("form");

form.addEventListener("submit", function (event) {

  // This WILL run because the submit event IS cancelable
  if (event.cancelable) {
    event.preventDefault();
  }

});

If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!