The One with Event Propagation and e.preventDefault() — PART 1
Events on your webpage cause some action to happen. It brings interactivity to your webpage. For example, the click on a button — it’s an event — “click” event to be precise. So you trigger an event with that click and some action happens.
There are so many events — you have one for changing of some value in a field, you have for scrolling on a page, there are events even for knowing when the mouse enters or leaves a certain element on the page.
There is a flow of these events triggering. Let’s suppose an example of nested
divs. In this example, there are 3 level nesting of these
divs and all of them have a function subscribed in case of a 'click' event.
Now try and execute this markup (after styling them as you like). Click on the child ‘C’. What happens?
If everything went well, you should get 3 alerts — first C, then B and last A. What you witnessed is a form of event flow called Event Bubbling.
Event Bubbling is when the event triggering starts from the target element all the way to the parent (even the document and window element) — so in a manner of speaking the event bubbles up. This is what happens by default on modern browsers.
Other type is the Event Capturing wherein the event starts from the parent element and then comes down to the target element. For this to happen, you need to pass in a third boolean parameter to the
We have control to cancel a default action on some event trigger. Popular use case is cancelling the default action of Submitting a Form on click of the submit button to perform some custom action.
In the above example, we are calling a preventDefault method on the click event on ‘B’. What this does is cancel the default behavior (if it is cancelable). It is important to note that not all event can be cancelled. You can if a particular event is cancelable using the property
cancelable on the event.
Stop event propagation
I don’t need event propagation — any way to opt out of this? Yes there is — using
event.stopImmediatePropagation(). These methods cancel the propagation of the event - so if some event is triggered on the child element, the event never bubbles up to the parent element (or capture down to further child element) thereby cancelling the action on them.
The difference between these two is that
event.stopPropagation stops the propagation of the event further up or down the DOM tree so in case there are multiple handlers on the event, they all will still execute but only on the target element(where the event is registered). Whereas in
event.stopImmediatePropagation, even if there are multiple handlers (say multiple actions on the same target for same event), all are cancelled.
That’s all about events for now. Let’s look into an interesting problem in Part 2.