Skip to main content

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 / eventBrowser's default behavior
<a href="..."> + clicknavigating to the link
<form> + submitsubmitting the form and reloading the page
<input type="text"> + keypress Entercan trigger a form submission
Context menu (contextmenu)opening the right-click menu
<checkbox> + clickchanging the state (checked/unchecked)

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, use stopImmediatePropagation().
  • It works only with events that have a default behavior. For example, on a div click it does nothing, because clicking a div does not trigger any default action.

Summary

MethodWhat it doesExample
event.preventDefault()Cancels the browser's behaviorDon't navigate the link, don't submit the form
event.stopPropagation()Stops the event from bubblingDon't pass the event to parents
event.stopImmediatePropagation()Fully stops all handlersInterrupt everything

Remember it simply: preventDefault(): "Don't perform the default action!" stopPropagation(): "Don't bubble the event up!"

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.