event.preventDefault(): Canceling Default Behavior
What you'll learn: How to stop the browser from performing its default action when an event occurs.
The Problem with Default Behaviors
Browsers have built-in responses to certain events. When you click a link, the browser navigates to a new page. When you submit a form, it refreshes the page and sends data to a server. Sometimes, though, you want to handle these actions yourself with JavaScript instead of letting the browser do its thing.
Think of it like intercepting a letter before it gets mailed — you catch it, do what you need to do with it, and decide whether to actually send it or not.
Using preventDefault()
The Event object (which you've already learned about) has a method called preventDefault() that tells the browser: "Don't do your usual thing for this event." You call it inside your event handler function:
const link = document.querySelector('a');
link.addEventListener('click', function(event) {
event.preventDefault(); // Link won't navigate
console.log('Link clicked, but not following it!');
});
Common Use Cases
Preventing form submission (to validate first):
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
console.log('Form submitted, but page won't refresh');
// You can now validate or send data with JavaScript
});
Stopping link navigation (for single-page apps):
const menuLink = document.querySelector('#menu-link');
menuLink.addEventListener('click', function(event) {
event.preventDefault();
// Handle navigation with JavaScript instead
});
When NOT to Use It
Don't prevent default behavior unless you have a good reason and are replacing it with your own logic. Users expect links to work and forms to submit!
Key Takeaway: event.preventDefault() stops the browser's default action for an event, giving you full control to handle the interaction with JavaScript instead — essential for custom form handling and single-page applications.