- Oscar Dominguez
According to Mozilla Developer Network documentation
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
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:
clickevent is triggered
- 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
- Also, the
clickeventHandler for its parent element (
<form>) is executed too. In this case, the styling
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: