Pages

Event Propagation In JS

Event Propagation?


When an event occurs on a DOM element, that event does not entirely occur on that just one element. In the Bubbling Phase, the event bubbles up or it goes to its parent, to its grandparents, to its grandparent's parent until it reaches all the way to the window while in the Capturing Phase the event starts from the window down to the element that triggered the event or the event.target.
Event Propagation has three phases.
  1. Capturing Phase the event starts from window then goes down to every element until it reaches the target element.
  2. Target Phase – the event has reached the target element.
  3. Bubbling Phase – the event bubbles up from the target element then goes up every element until it reaches the window.

EVENT BUBBLING AND EVENT CAPTURING IN JAVASCRIPT


Bubbling Phase

When an event occurs on a DOM element, that event does not entirely occur on that just one element. In the Bubbling Phase, the event bubbles up or it goes to its parent, to its grandparents, to its grandparent's parent until it reaches all the way to the window.

Capturing Phase
When an event occurs on a DOM element, that event does not entirely occur on that just one element. In Capturing Phase, the event starts from the window all the way down to the element that triggered the event.
Example-1
<div id="parent">
    <button id="child">Child</button>
</div>
// element.addEventListener(event, function, useCapture); 
//Default value usecaption false for event bubling
//useCapture true for event capturing

var parent = document.querySelector('#parent');
var child = document.querySelector('#child');

parent.addEventListener('click', function(){
  console.log("Parent clicked");
},true);

child.addEventListener('click', function(){
  console.log("Child clicked");
});

Result:
//Parent clicked
//Child clicked
Example-2
event.target
form.onclick = function(event) {
  event.target.style.backgroundColor = 'yellow';
};