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).
