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
1function handleClick(event) {2 event.preventDefault();3 console.log('Link clicked');4}
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
1// Example 1: Form Submission2const form = document.querySelector('form');3form.addEventListener('submit', (e) => {4 e.preventDefault(); // Stop form from submitting normally56 // Now we can handle the form submission with AJAX7 const formData = new FormData(form);8 submitFormWithAjax(formData);9});
Preventing default behaviour of a link
JAVASCRIPT
1const link = document.querySelector('#myLink');2link.addEventListener('click', (e) => {3 e.preventDefault(); // Stop navigation45 // Custom handling instead6 showModalDialog();7});
Preventing right click
JAVASCRIPT
1document.addEventListener('contextmenu', (e) => {2 e.preventDefault(); // Stop browser context menu34 // Show custom context menu instead5 showCustomMenu(e.pageX, e.pageY);6});