Why you should understand Event Bubbling and Capturing Phase in Html?




Event bubbling

By default, events bubble in JavaScript. Event bubbling is when an event will traverse from the most inner nested HTML element and move up the DOM hierarchy until it arrives at the element which listens for the event. This move is also popularly known as Event Propagation or Event Delegation.


Scenario 1:
Handler is registered on parent but not on child:

On clicking on Inner Div, the event bubbles up and event handler of outerDiv will get executed.

outer div got clicked

Scenario 2:
Handler is registered on both parent and child:

inner div got clicked
outer div got clicked

Event Capturing:

Events propagate from the Window down through the DOM tree to the target node.
Example, if the user clicks a hyperlink, that click event would pass through the <html> element, the <body> element, and the <p> element containing the link.

Explanation of Technical aspects:

Below link explains the Event propagation mechanism very clearly.

Event Phases

  1. The capture phase: the event is dispatched to the target’s ancestors from the root of the tree to the direct parent of the target node.
  2. The target phase: the event is dispatched to the target node.
  3. The bubbling phase: the event is dispatched to the target’s ancestors from the direct parent of the target node to the root of the tree.

Very important note: Some events may not necessarily accomplish the three phases of the DOM event flow, e.g. the event could only be defined for one or two phases. As an example, events defined in this specification will always accomplish the capture and target phases but some will not accomplish the bubbling phase (“bubbling events” versus “non-bubbling events”, see also the Event.bubbles attribute).

Summary of the above information:

When an event occurs in an html page, we can say that it occurs on an html element or node which we call as Target.
Example: We clicked on a button element.

This click event can reach the button through 2 phases.
1) From it’s parent through Capturing phase
2) Since the event occurred on the button, event reaches the button first and then this event bubbles up to it’s parent.

An Html element can have handlers for Bubbling phase or Capturing phase. So how to have such handler?

addEventListener method

JavaScript has a built-in method called addEventListener which you can append onto HTML nodes. It takes in a total number of 3 arguments as follows:

  1. Name of an event.
  2. The callback function to run some code when the specified event is triggered.
  3. Optional: the Boolean value of capture. (Set to false by default).

To register handler for capturing phase,
elem.addEventListener(…, {capture: true})