Does the JavaScript "preventDefault()" Method Stop Event Propagation?

Calling the Event.preventDefault() method on a JavaScript event object only prevents the default action of an event associated with an element from occurring. It does not stop event propagation. You can see this demonstrated in the example below:

<div id="parent" style="padding: 20px; background-color: pink;">
  <button id="child">Click me</button>
</div>
document.getElementById('parent').addEventListener('click', function() {
  console.log('Parent clicked');
});

document.getElementById('child').addEventListener('click', function(event) {
  event.preventDefault();
  console.log('Child clicked');
});

If you click the button in this example, the following output will be logged in the console:

Child clicked
Parent clicked

As you can see in the example above, the event bubbles up, which means event propagation is not stopped.

If you want to stop event propagation in addition to preventing the default action, then you can call both, the Event.preventDefault() method and the Event.stopPropagation() method, on the event object within your event listener function:

element.addEventListener('click', function(event) {
  event.preventDefault();
  event.stopPropagation();
  // ...
});

Therefore, to prevent default and stop propagation together, you can rewrite the earlier example as follows:

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

document.getElementById('child').addEventListener('click', function(event) {
  event.preventDefault();
  event.stopPropagation()
  console.log('Child clicked');
});

Based on the code above, if you click the child element, the event will not be propagated beyond the child, producing the following output:

Child clicked

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.