We usually use an event to an element and whenever that event occurs to an element then the attached event to that element is fired. But we don’t know how JavaScript performs the event in the DOM. Today we will learn about the JavaScript Event Propagation means how JavaScript propagates the event between the parent and his child elements.
The standard DOM Event describes 3 phases of event propagations.
- Capturing Phase
- Target Phase
- Bubbling Phase
Before I start from the Capturing phase I want to start from the Bubbling Phase as it’s the default process of JavaScript.
So let’s take an example :-
In the above example I have applied same event handler to both parent and his child elements.
So the point is – which event will be performed first if the click event is occurred to the child element (id equal to div3) ?
In default JavaScript process all the event will be performed from child to parent that’s called JavaScript Bubbling.
In JavaScript Bubbling whenever event is performed on the element then browser checks the whether same event is applied on the parent element, If yes, then browser performed that event for the parent just after the target element on which the actual event is fired.
But JavaScript Capturing is just opposite to the JavaScript Bubbling means event performed from parent to the target element. This can be achieved by passes third parameter as a true of JavaScript “addEventListener” function.
If now click event is performed on the child element (id equals to div3) then the event performs for the parent first and then the child element.
Note – In JavaScript if we use the capturing process then bubbling process also works.
Just look at the above example. After the event is performed to the parent element browser perform the event for the target element and then that event will be performed for the element (id equals to div2). That’s the bubbling process worked after the capturing.
I hope this article will help you to understand about the Event Propagation of JavaScript.
2 comments
When the event arrives at its target then it’s called Target Phase. As per the example is given in the blog, when you click on #div1 and the window gives alert the same that is div1 then it is the Target Phase.
You can check the phase of an event by event.eventPhase.
Example:
document.getElementById('div1').addEventListener('click', function(event) {
console.log(event.eventPhase);
});
The eventPhase has the values 1, 2 and 3 of Capturing Phase, Target Phase, and Bubbling Phase respectively.