Published on

What is Event.preventDefault() for?

Authors

According to Mozilla Developer Network documentation:

Event.preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

This means that, when .preventDefault() is used in an eventHandler for an HTML Element, browser's default behavior assigned to that event for that element simply will not occur.

An example based on the one in MDN documentation where this can be understood is the following one:

Take a look at this simple checkbox. If you check the source code, there is an eventHandler for the click event for the checkbox element so, when a user does a click on the checkbox:

  1. The click event will be triggered

  2. The eventHandler will execute the lines of code, in this case:

    • if checkbox is not checked, apply red border to <form> ☑️
    • if checkbox is checked, remove red border to <form> ◽.
  3. The browser will apply the default behavior to the element which is:

    • if checkbox is not checked, check it ☑️
    • if checkbox is checked, uncheck it ◽.

You can play with it here:

Instead, when we create an eventHandler to manage the click event for the checkbox HTML element, and we add a event.preventDefault() sentence, the click event is managed in the following way:

  1. The click event will be triggered

  2. The eventHandler will execute the lines of code, in this case:

    • if checkbox is not checked, apply red border to <form> ☑️
    • if checkbox is checked, remove red border to <form> ◽.
  3. The browser will NOT apply the default behavior to the element so the checkbox will not be marked.

The rest of clicks will not apply any change because the checked or not checked logic stopped working with preventDefault()