CodePark/ questions / DOM & events
START PRACTICINGPRACTICE
Frontend question · JavaScript › DOM & events

What is the difference between event.preventDefault() and event.stopPropagation()?

They control different things. preventDefault() stops the browser's default action. stopPropagation() stops the event from reaching other elements.

preventDefault():

  • It cancels the browser's default action for the event. For example, a link does not navigate, a form does not submit and reload the page, and a checkbox does not toggle.
  • The event still travels to other listeners as normal.
  • It only works if the event is cancelable.
  • It is ignored in listeners registered with passive: true.

stopPropagation():

  • It stops the event from moving to other elements in the capture or bubble path. So listeners on ancestors do not run.
  • It does not cancel the default action.
  • Other listeners on the same element still run. stopImmediatePropagation() stops those too.

Use stopPropagation rarely. It breaks delegated listeners and analytics code higher up the page.

  • preventDefault cancels the browser's default action, but does not stop propagation.
  • stopPropagation stops the event reaching other elements, but does not cancel the default action.
  • stopImmediatePropagation also skips the remaining listeners on the same element.
  • preventDefault is ignored in passive listeners.