What Does the JavaScript "preventDefault()" Method Do?

The Event.preventDefault() method is a built-in function in JavaScript which is used to prevent the default action of an event associated with an element from occurring.

When an event is triggered in a web browser, such as a clicking on a link or a submission of a form, the browser performs a default action associated with that event. The Event.preventDefault() method allows you to stop this default action from happening, giving you more control over the behavior of HTML elements on your web page.

For example, if you have a link, you can use the Event.preventDefault() method to stop the link from navigating to the URL specified in the href attribute when it is clicked (as demonstrated in the following example):

<a id="lnk" href="https://google.com">Google</a>
document.getElementById('lnk').addEventListener('click', function (event) {
  event.preventDefault();
  console.log('Link clicked, but default action prevented!');
});

If you click the link in this example, the following output will be logged in the console:

Link clicked, but default action prevented!

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.