What does preventDefault() do?
JavaScript Important
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.
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
// 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);
});
Preventing default behaviour of a link
const link = document.querySelector('#myLink');
link.addEventListener('click', (e) => {
e.preventDefault(); // Stop navigation
// Custom handling instead
showModalDialog();
});
Preventing right click
document.addEventListener('contextmenu', (e) => {
e.preventDefault(); // Stop browser context menu
// Show custom context menu instead
showCustomMenu(e.pageX, e.pageY);
});
00:00