Understanding e.preventDefault() better

It's pretty common that many of us use event.preventDefault and return false on a click event or any other event. Lets see event.preventDefault() first. The function name itself more or less tells the story, that it will prevents the default action on any event.

event.preventDefault() — Cancels the event if it is cancelable, without stopping further propagation of the event.

Let's see an example, say in your awesome cool website you have a link to google.com and you want to show google.com in a modal window instead opening up in the new tab, then you will do something similar to below.

$("a.open_modal").click(function(event) {
  // Open modal

The example above is specific to jQuery, However preventDefault() is a JavaScript function on an event. Most of the developers think that preventDefault() is a jQuery function but its not. See the below example

<!DOCTYPE html>
    <title>preventDefault example</title>
      function stopDefAction(evt) {
        alert("You shall not pass!!");
      function Init() {
          .addEventListener("submit", stopDefAction, false);
  <body onload="Init()">
    <p>Please click on the submit button.</p>
    <form id="my-form">
      <input type="checkbox" id="my-checkbox" />
      <label for="my-checkbox">Checkbox</label>
      <input type="submit" value="Submit" />

Above example stops the normal form submit when you click on the submit button. See in action below

preventDefault example


So now we successfully prevented the default action, now you may ask how do I find out the event is prevented or not. As of Gecko 6.0, calling preventDefault() causes the event.defaultPrevented property's value to become true. In short event.preventDefault() will make the boolean event.defaultPrevented true. A simple if condition to check if default is prevented or not.

event.defaultPrevented is a boolean turned to true when event.preventDefault() is called.

if (e.defaultPrevented) {
  // the default was prevented

Browser support for event.defaultPrevented

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 18 6.0 (6.0) 9.0 11.0 5.0

Before using event.preventDefault make sure if the event default event can be preventable with event.cancelable function. You can use event.cancelable to check if the event is cancelable. Calling preventDefault for a non-cancelable event has no effect.

NOTE: preventDefault doesn't stop further propagation of the event through the DOM. event.stopPropagation should be used for that.

Further reading

Last Updated: 5/11/2019, 1:38:42 AM
Siddhartha Gudipati
I'm Sid, a designer. I write about my random thoughts, some tech, ux and also post pictures I clicked with my Sony a7iii. If you enjoy content follow me on twitter.