Curriculum Series

What does preventDefault() do?

What does preventDefault() do?

What does preventDefault() do?

JavaScript

preventDefault()

preventDefault() is a method in JavaScript that cancels an event's default behavior that the browser would normally execute. Every browser event (like clicking a link, submitting a form, or pressing a key) has some default behavior associated with it.

javascript
function handleClick(event) {
event.preventDefault();
console.log('Link clicked');
}

The key thing to remember is that preventDefault() must be called early in your event handler - before any default behavior can occur. Once you prevent the default behavior, you're free to implement whatever custom behavior you want instead.

This is particularly useful in modern web applications where you often want to:

  • Handle form submissions without page reloads
  • Create custom navigation systems
  • Implement custom UI interactions
  • Validate data before allowing an action to proceed
  • Create single-page applications (SPAs)

Preventing default behaviour of an event

javascript
// Example 1: Form Submission
const form = document.querySelector('form');
form.addEventListener('submit', (e) => {
e.preventDefault(); // Stop form from submitting normally
// Now we can handle the form submission with AJAX
const formData = new FormData(form);
submitFormWithAjax(formData);
});
javascript
const link = document.querySelector('#myLink');
link.addEventListener('click', (e) => {
e.preventDefault(); // Stop navigation
// Custom handling instead
showModalDialog();
});

Preventing right click

javascript
document.addEventListener('contextmenu', (e) => {
e.preventDefault(); // Stop browser context menu
// Show custom context menu instead
showCustomMenu(e.pageX, e.pageY);
});

Finished reading?

Mark this topic as solved to track your progress.