Event Bubbling And Event Capturing

In HTML, DOM elements are nested inside each other. Sometimes, we need to fire an event from parent elements to child or child to parent in the nested elements. Event bubbling and capturing are the concepts in JavaScript for understand, how to fire an event from parent to child or child to parent.

Event Bubbling

Sometimes, parent element event handler also executes, even if we click on child element.

For example, In the example, given below, "a" tag event handler executes, even if we click on "p" tag.

  1. <a onclick="alert('hi')">  
  2.    <p>This is a paragraph.</p>  
  3. </a>  
That’s because an event bubbles from the nested tag up and triggers the parent. In the above case, first inner most element event is called, followed by calling parent event. Thus, we call bubbling order like bubble of air in the water.

Stopping Event Bubbling

The bubbling goes right to the top. When an event occurs on an element - it will bubble up to <HTML>, triggering handlers are on it’s way.

A handler may decide that an event is fully processed and stop the bubbling.

The code is given below-

event.stopPropagation()

or

for IE < 9
event.cancelBubble = true


Event Capturing

In Event Capturing, an event is executed in parent to child element.
  1. <a onclick="alert('hi')">  
  2.    <p>This is a paragraph.</p>  
  3. </a>  
In the example, stated above, If we want to execute "a" tag event handler first. We need to do event capturing on the element.

All the methods of event handling ignore the caputiring phase. Using addEventListener with last argumenttrue is only the way to catch the event at capturing.

Code
  1. elem.addEventListener( type, handler, phase )  
  2. phase = true  
The handler is set on the capturing phase.

phase = false

The handler is set on the bubbling phase. 
Ebook Download
View all
Learn
View all