How to prevent default action of an event in JavaScript

published: 17 Jul 2022

2 min read

How to prevent default action of an event in JavaScript

To prevent the default action of an event, you can call the Event.preventDefault() method. This method cancels the event if it is cancelable:

Event.preventDefault();

Note that the preventDefault() method does not prevent further propagation of an event through the DOM. To explicitly stop the event propagation, use the stopPropagation() method in the event handler.

Let us say you have got the following HTML code snippet:

<form action='/signup' method='GET' id='forms'>
    <button id='signup' type='submit'>Sign Up</button>
</form>

When you click on the button, the HTML <form> is submitted.

To prevent the button from submitting the form, just call the preventDefault() method in the button's event handler:

const btn = document.querySelector('#signup');

btn.addEventListener('click', (e) => {
    e.preventDefault();

    alert('Unable to submit the form.');
});

The Event.preventDefault() method works in all modern browsers, and IE9 and above.

How to prevent default action of an event in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming