HomeJAVASCRIPTHow do you prevent default behavior of events?

How do you prevent default behavior of events?

In JavaScript, you can prevent the default behavior of an event by using the event.preventDefault() method.

This is useful when you want to stop the browserโ€™s built-in behavior (like following a link, submitting a form, refreshing on Enter, etc.) and instead handle the behavior with your own logic.


โœ… Syntax:

element.addEventListener("eventName", function(event) {
    event.preventDefault();
});

๐Ÿ“Œ Example 1: Prevent link from navigating

document.querySelector("a").addEventListener("click", function(event) {
    event.preventDefault(); // stops navigation
    console.log("Link click prevented!");
});

๐Ÿ“Œ Example 2: Prevent form submission

document.querySelector("form").addEventListener("submit", function(event) {
    event.preventDefault(); // stops form from submitting
    console.log("Form submission prevented!");
});

๐Ÿ“Œ Example 3: Prevent right-click menu

document.addEventListener("contextmenu", function(event) {
    event.preventDefault(); // disables right-click menu
    console.log("Right-click disabled!");
});

๐Ÿ”น Key point:
preventDefault() only prevents the default browser action, not other event listeners.
If you want to stop the event from going further through the bubbling/capturing phase, use event.stopPropagation() (or event.stopImmediatePropagation() if multiple handlers are attached).

Share:ย 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *