What’s the difference between event.preventDefault and event.stopPropagation?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Medium
#JavaScript #DOM #Events

Brief Answer

  • event.preventDefault() — cancels the browser’s default action (link navigation, form submit), while the event still propagates.
  • event.stopPropagation() — stops propagation through the tree (bubble/capture), while the default action remains.
  • Need both? Call both methods on the same event.

Full Answer

What preventDefault does

Cancels the element’s default behavior:

  • A link doesn’t navigate to href.
  • A form doesn’t submit.
  • Context menu doesn’t open, etc.

The event still propagates, so parent handlers will run.

Mini example:

// Link won’t navigate; parent handler still runs
parent.addEventListener('click', () => console.log('parent'));
link.addEventListener('click', (e) => {
  e.preventDefault();
  console.log('link');
});

What stopPropagation does

Stops further propagation (down the capture phase or up the bubble phase). The default browser action is not canceled.

Mini example:

// Click on button doesn’t reach parent; the button’s default action remains
card.addEventListener('click', () => console.log('card'));
button.addEventListener('click', (e) => {
  e.stopPropagation();
  console.log('button');
});

Common misconceptions

  • stopPropagation does not cancel the default action — use preventDefault.
  • preventDefault does not stop propagation — use stopPropagation.
  • To stop propagation and prevent other handlers on the same element, use event.stopImmediatePropagation().

When to call both

If a nested link inside a card should:

  • not navigate (preventDefault),
  • not trigger the card’s click handler (stopPropagation),

call both:

link.addEventListener('click', (e) => {
  e.preventDefault();
  e.stopPropagation();
});

In React

In React’s synthetic events these methods behave like DOM:

  • e.preventDefault() — cancels the action.
  • e.stopPropagation() — halts propagation. Remember onClickCapture runs in the capture phase before onClick.