Language: EN

javascript-prevent-default

What is PreventDefault and How to Use It in JavaScript

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

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

  • Submitting a form by clicking a submit button
  • Navigating to a new page by clicking a link

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

However, sometimes we need to prevent them from happening because we want to do something different (or a prior action, such as 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 is 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 tries 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();
});

In this case:

  • Although the link points to an external page, clicking on it will not navigate to the specified URL.
  • Instead, the message “The link has not been followed” will be printed in the console.
  • This happens because we have used event.preventDefault(), which prevents the default action of the link (navigation) from occurring.

Practical examples