DEV Community

Scott
Scott

Posted on

When should you use event.preventDefault()

All too often I see event.preventDefault() sprinkled through applications where it doesn't make a whole lot of sense.

You should be using this method to prevent the default action of an event....easy enough, right?. Well no.

The conversation should NOT go:

Oh theres an event being handled, lets add an event.preventDefault()

If you take ANYTHING away from this article, please ASK WHY if you dont know why something is happening. You will learn and make a much more informed decision.

Back to my soap box.....

The only examples I can think you would want to use this is during the following cases AND to prevent their default action (please comment below if you can think of any more):

  • Checkbox
    • Default action: input being checked
  • Button with type submit
    • Default action: Submitting the form data
  • Input with an onChange handler
    • Default Action: Adding the text to the input
  • Link tag
    • Default Action: Visiting the link

Lets do an example

What do I want to accomplish? I want to click a link and do something instead of allow the user to go to the href specified in the tag.

Lets Assume I have an a tag that looks like this

<a class="dev-test" href="https://example.com">Click Here</a>
Enter fullscreen mode Exit fullscreen mode
const el = document.getElementsByClassName('dev-test')[0];

el.addEventListener('click', e => {
  e.preventDefault();
  // Do something else.
});
Enter fullscreen mode Exit fullscreen mode

Here is a codepen to play around with this concept

HOT TIP ALERT

  1. Click the link and see what happens.
  2. Comment out the e.preventDefault(), then click the link and see what happens.

What do all of these have in common? They all have a default action that can be prevented.

So, in s u m a t i o n, next time you come across a preventDefault in the wild, think, "what action am I preventing and why is this here?"

For more information on the official spec you can read more here.

Hope you enjoyed reading! If you have any comments, questions or topics you want me to go over please comment below!

Top comments (1)

Collapse
 
adgower profile image
Alex Gower

Thanks