Difference-Between-Event.Preventdefault-And-Event.Stoppropagation

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

  • Profile picture of Mcs
  • by Mcs July 2, 2025

preventDefault() is used to prevent the browser from executing the default action associated with the event. It tells the browser not to perform its default behavior for the event. event. stopPropagation() is used to stop the event from propagating further in the DOM hierarchy.

event.preventDefault() and event.stopPropagation() are both methods available on the JavaScript Event object, but they serve very different purposes when dealing with events in the DOM. Here's a breakdown:

event.preventDefault()

Purpose:

Prevents the default browser behavior associated with the event.

Examples:

  • Preventing a form from submitting.
  • Preventing a link (<a>) from navigating to a new page.
  • Preventing scrolling when pressing arrow keys.

Use case example:

document.querySelector('a').addEventListener('click', function(event) {
   event.preventDefault(); // Stops the browser from navigating
   console.log('Link clicked, but not navigating');
});

event.stopPropagation()

Purpose:

Prevents the event from bubbling up to parent elements.

This means the event will not propagate beyond the current element.

Use case example:

document.querySelector('.child').addEventListener('click', function(event) {
   event.stopPropagation(); // Stops the event from bubbling up
   console.log('Child clicked, but event won’t reach parent');
});

document.querySelector('.parent').addEventListener('click', function(event) {
   console.log('Parent clicked');
});

If .child is inside .parent, clicking the child will only trigger the child’s handler, not the parent’s.

Summary Table:

MethodPrevents default browser behaviorStops event bubbling
event.preventDefault()YesNo
event.stopPropagation()NoYes

Bonus: event.stopImmediatePropagation()

  • Stops propagation and prevents other handlers of the same event on the same element from firing.

Conclusion

  • event.preventDefault(): Stops the browser’s default action (e.g., following a link or submitting a form).
  • event.stopPropagation(): Stops the event from bubbling up to parent elements.