Published on

Event.preventDefault() vs. Event.stopPropagation()

Authors

According to Mozilla Developer Network documentation preventDefault()'s definition:

Event.preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

It is important to consider also this detail on how preventDefault is interpreted by the browser:

The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

What this means is, when an event is triggered for a certain HTML Element, this same event will be propagated for its parent elements.

You can find an example in the following snippet of code:

As you can see, when you click on the checkbox:

  1. the click event is triggered
  2. The eventHandler associated to checkbox is executed. In this case, it displays or hides a border to <form> element alternatively. The checkbox default behavior of adding or removing a tick to the checkbox is not happening due to preventDefault() sentence.
  3. Also, the click eventHandler for its parent element (<form>) is executed too. In this case, the styling color changes to red or green alternatively.

If you want to read more about preventDefault you can take a look to my blog post. Also, you can read more about the capturing and bubbling phases of Events in Mozilla Developer Network documentation.

On the other hand, if we apply the .stopPropagation() method, the result we will obtain is to assure the click event does not bubble up to parent elements.

You can play with the following snippet of code where you can see the differences: