cover-img

How to Prevent The Default Behaviour of an Event?

20 January, 2023

3

3

0

In JavaScript, the default behaviour of certain events, such as a form submission or a link click, can be prevented using the preventDefault() method of the event object.

For example, when a user submits a form, the browser will typically refresh the page and clear the form's fields by default. To prevent this behaviour and handle the form submission with JavaScript instead, you can call preventDefault() on the event object in the form's submit event listener:

var form = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
event.preventDefault();
// do something with the form data
});

Another example is when you want to handle the click event of an anchor tag but you want to prevent it from navigating to the href link

var link = document.getElementById("myLink");
link.addEventListener("click", function(event) {
event.preventDefault();
// do something with the link
});

By calling preventDefault() on the event object, the browser's default behaviour is cancelled. The form will not be submitted, or the link will not navigate to the destination, allowing you to handle the event with JavaScript instead.

It's important to note that preventDefault() only prevents the default behaviour of the event. It doesn't stop the event from propagating to parent elements you can use stopPropagation() method for that. Also, the effect of preventDefault() can vary between different types of events, so you should be aware of the expected behaviour of the events you are handling.

Let’s understand preventDefault() with an example:

The <a> tag has a link heading to showwcase.com and it is the default behaviour of a link to open the mentioned URL when clicked. But when the checkbox is checked, preventDefault() is called on our event object e. Now, any number of clicks won’t head us to the desired URL as the default behaviour of the link is being stopped.

3

3

0

ShowwcaseHQ

San Francisco, CA, USA

Showwcase is where developers hang out and find new opportunities together as a community
Vedamruta Udavant
I met my love and that is programming !! Currently learning JS :)

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.