javascript-prevent-default

What is PreventDefault and How to Use It in JavaScript

  • 4 min

In JavaScript, the preventDefault method allows us to prevent the default action associated with an event from being performed.

The default action is the one defined by the browser when an event occurs on an element. For example:

  • Submitting a form when clicking a button of type submit
  • Navigating to a new page when clicking a link

In general, the default action is useful, and it’s what we want to do in most cases.

But sometimes, we need to prevent them from happening because we want to do something else (or a prior action, like validation).

For this, we have the preventDefault method, which is available on the Event object. By invoking it, we can “stop” these default actions.

Avoid unnecessary use: If there is no specific reason to prevent the default action, it’s better not to use preventDefault.

How does preventDefault work?

Let’s see how it works with a simple example. For instance, when we click on a link, the browser attempts to navigate to a new URL.

If we use preventDefault on the click event, we prevent the browser from performing this navigation.

const link = document.querySelector('a');
link.addEventListener('click', (event) => {
  event.preventDefault();
});
Copied!

In this case:

  • Even though the link points to an external page, clicking on it will not navigate to the specified URL.
  • Instead, the message “The link was not followed” will be printed to the console.
  • This happens because we used event.preventDefault(), which prevents the link’s default action (navigation) from taking place.

Practical Examples