Course contentsShow
← Web Development
Lesson 724 of 2,98213. DOM EventsFree lesson

preventDefault() Method

Canceling default browser behaviors like form submissions and link navigation with preventDefault().

preventDefault() Method

What you'll learn: How to stop the browser's default response to an event and take full control of what happens instead.

What Is preventDefault()?

When certain events occur—like clicking a link, submitting a form, or right-clicking on a page—browsers have built-in behaviors they automatically execute. The preventDefault() method lets you cancel these default actions so you can replace them with your own custom logic.

Think of it like catching a ball before it hits the ground. The browser is about to do something automatically (the ball falling), but you intercept it first (preventDefault()) and decide what happens next.

Common Use Cases

Preventing Form Submission:

const form = document.querySelector('form');

form.addEventListener('submit', function(event) {
  event.preventDefault();
  // Now you can validate or submit via AJAX instead
  console.log('Form submitted, but page did not reload');
});

Stopping Link Navigation:

const link = document.querySelector('a');

link.addEventListener('click', function(event) {
  event.preventDefault();
  // Link won't navigate, you control what happens
  console.log('Link clicked but did not navigate');
});

How It Works

Call preventDefault() on the event object passed to your handler function. It must be called before the browser processes the default action—usually right at the start of your handler.

Remember: preventDefault() only stops the default browser behavior. It does not stop event bubbling (that's what stopPropagation() does).

Key Takeaway: preventDefault() cancels the browser's built-in response to an event, giving you complete control to define custom behavior instead—essential for forms, links, and interactive web applications.