Event Bubbling and Event Capturing

Event Bubbling and Event Capturing

During an interview interviewer asked me one question, that question is what is the third argument of addEventListener

at that time i dont know about third argument then i came to know that third argument handles with event bubbling and capturing so let's learn event bubbling and capturing

An event listener contains three parameters and it can be defined using the following syntax.

<element>.addEventListener(<eventName>, 
    <callbackFunction>, {capture : boolean});

{capture : boolean} is an optional argument which tell's us whether the event will be in the capture phase or in the bubbling phase

so lets understand what is capture phase and bubbling phase through an example

<div onclick="alert('The handler!')">
     <p>Click on me</p>
</div>

in the above code alert handler is given to div element but still it will trigger if we click on nested elements,here that is para element

// Why does the handler on div run if the actual click was on p elemnt ?

Bubbling

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.

so in the above example after happening of event on the p element,JS check that is there any handlers on current element if yes JS will execute that then it will goes to the parent element to check is there any handlers on parent if yes it will executes that as well and then all the way up on other ancestors.

The process is called “bubbling”, because events “bubble” from the inner element up through parents.

Pitfall in Bubbling

Almost all the events bubbles up but few doesn't, examples are Focus event and e.t.c

Target Element

While executing different handlers(during bubbling process) if we want to know which is the element on which event happend we will get that by (e.target) this won't change during entire process

to get current element (currently executing handler element ) we will get that by (e.currentTarget) this will change during bubbling process

Capturing phase

this phase is quite opposite to the bubbling phase so in bubbling exection goes from target element to root element but in capturing phase execution goes from root element to target element so during this phase we can able executes handlers, from root to target element in sequential manner like first executes the handler of parent and then child handler and then child's child handlers so on... which is exactly opposite to bubbling

event handlers during capture phase will executes only if we give {capture:true} as third argument to addEventlistener if not handlers will execute only during bubbling phase

refer below diagram for more understanding

event.jpeg