Taking Control
Many HTML elements have built-in default behaviors that the browser performs automatically:
- Clicking a link → navigates to its URL.
- Clicking a submit button → submits the form.
- Scrolling the mouse wheel → scrolls the page.
- Right-clicking → opens the context menu.
How to Cancel a Default Action
Call event.preventDefault() inside your handler:
const link = document.querySelector('a');
link.addEventListener('click', function(event) {
event.preventDefault(); // The link will no longer navigate!
alert('Navigation was cancelled. We handle this ourselves.');
});
A Common Real-World Use Case
Custom form validation: prevent the form from submitting until all fields pass your checks.
form.addEventListener('submit', function(event) {
if (!isFormValid()) {
event.preventDefault(); // Don't submit yet!
showErrors();
}
});
Important
Be careful: if you cancel the mousedown event on a text input, you'll prevent it from receiving keyboard focus when clicked. Always test your preventDefault() calls thoroughly!