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 Submissionconst form = document.querySelector('form');form.addEventListener('submit', (e) => {e.preventDefault(); // Stop form from submitting normally// Now we can handle the form submission with AJAXconst formData = new FormData(form);submitFormWithAjax(formData);});
Preventing default behaviour of a link
javascript
const link = document.querySelector('#myLink');link.addEventListener('click', (e) => {e.preventDefault(); // Stop navigation// Custom handling insteadshowModalDialog();});
Preventing right click
javascript
document.addEventListener('contextmenu', (e) => {e.preventDefault(); // Stop browser context menu// Show custom context menu insteadshowCustomMenu(e.pageX, e.pageY);});