What does event.preventDefault() do?
Definition
event.preventDefault()cancels the default behavior the browser performs for a given event.
The event still happens (the handlers still run), but the browser does not perform its standard action.
Examples of default actions
| Element / event | Browser's default behavior |
|---|---|
<a href="..."> + click | navigating to the link |
<form> + submit | submitting the form and reloading the page |
<input type="text"> + keypress Enter | can trigger a form submission |
Context menu (contextmenu) | opening the right-click menu |
<checkbox> + click | changing the state (checked/unchecked) |
Example 1: canceling a link navigation
javascript
<a href="https://google.com" id="link">Go</a>
<script>
const link = document.querySelector('#link');
link.addEventListener('click', (event) => {
event.preventDefault(); // cancel the navigation
console.log('Link clicked, but no navigation happens');
});
</script>A message appears in the console, but the page does not navigate to Google.
Example 2: preventing a form submission
javascript
<form id="login">
<input type="text" name="login" />
<button>Submit</button>
</form>
<script>
const form = document.querySelector('#login');
form.addEventListener('submit', (event) => {
event.preventDefault(); // do not let the form reload the page
console.log('The form is handled manually via JS');
});
</script>Usually used when you want to send data via JavaScript (fetch, axios) instead of a regular HTML submission.
Example 3: disabling the context menu
javascript
document.addEventListener('contextmenu', (event) => {
event.preventDefault();
console.log('Context menu disabled!');
});Now a right-click will not open the standard menu.
Example 4: combined with stopPropagation()
Sometimes you need to both cancel the action and stop the bubbling:
javascript
button.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
console.log('Click fully intercepted');
});Important
preventDefault()does not stop the event, other handlers (on the same element or higher up) still run. To stop everything, usestopImmediatePropagation().- It works only with events that have a default behavior. For example, on a
div clickit does nothing, because clicking adivdoes not trigger any default action.
Summary
| Method | What it does | Example |
|---|---|---|
event.preventDefault() | Cancels the browser's behavior | Don't navigate the link, don't submit the form |
event.stopPropagation() | Stops the event from bubbling | Don't pass the event to parents |
event.stopImmediatePropagation() | Fully stops all handlers | Interrupt everything |
Remember it simply:
preventDefault(): "Don't perform the default action!"stopPropagation(): "Don't bubble the event up!"
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.