Let’s first understand what does stopPropagation and preventDeault mean:
1. StopPropagation : In simple words stopPropagation stops event bubbling and event capturing.
Now, let’s see what is event bubbling, event bubbling means if you have a number of elements enclosed one inside the other, then clicking on the innermost element starts a chain of event originating from innermost event towards outer i.e events gets propagated outwards, as shown below.
On the other hand, event capturing is just the opposite of event bubbling which means that event chain starts propagating from top most element to the innermost element.
2. PreventDefault : It simply disables the basic action attached to a event. For example if you apply preventDefault to a submit button then clicking on submit will prevent the form from submitting.
Here are few examples to show how stopPropagation and preventDefault work:
Example without stopPropagation and preventDefault
Clicking on the image above First alerts “Image clicked”, then “Div clicked” and then you will be redirected to a image of bird
Example with stopPropagation
Clicking on the image above First alerts “Image clicked”, and then you will be redirected to a image of bird. You will not see alert “Div clicked” because we have used stopPropagation which stops event bubbling.
Example with preventDefault
Clicking on the image above First alerts “Image clicked”, then “Div clicked” . You will not be redirected to image because we have used preventDefault, which disables the action of the event i.e. to redirect to the hyperlink.