Contents

Frontend Development › JavaScript & TypeScript

preventDefault and stopPropagation

Cancelling default browser behavior or further event propagation.

Also known as: preventDefault, stopPropagation, event.preventDefault()

Two methods on the event object that people often confuse.

  • preventDefault() cancels the browser’s default action for the event.
  • stopPropagation() stops the event from travelling to other elements (bubbling).
form.addEventListener("submit", (e) => {
  e.preventDefault();               // don't reload the page
  sendWithFetch(new FormData(form));
});

link.addEventListener("click", (e) => {
  e.preventDefault();               // don't navigate
  openModal();
});

Default actions you may want to cancel

EventDefault
submit on a formsends the form and reloads the page
click on a linknavigates
keydowntypes the character, or triggers a shortcut
contextmenushows the right-click menu
dragover and dropthe browser opens the dropped file (cancel it to handle drops yourself)
wheel, touchmovescrolling

Differences

preventDefaultstopPropagation
Stops the browser’s own behavioryesno
Stops other listeners higher upnoyes
Other listeners on the same elementstill runstill run (use stopImmediatePropagation to stop them)

They are independent: you might need one, both or neither.

Cautions

  • Not every event is cancelable (check e.cancelable).
  • Passive listeners ({ passive: true }, the default for touchstart, wheel on some targets) can’t call preventDefault(). This is for scroll performance.
  • Don’t break accessibility: cancelling a link’s click with a <div> pretending to be a link loses keyboard behavior. Use real links and buttons.
  • Overusing stopPropagation breaks analytics and “click outside” handlers. Prefer checking e.target.
  • Return false from an inline handler is another way, but avoid inline handlers.