Explain the event flow process in Javascript


In the JavaScript, Event Flow process is completed by three concepts −

  • Event Target − The actual DOM object on which the event occured.

  • Event Bubbling − Explained below

  • Event Capturing − Explained below

Event bubbling is the order in which event handlers are called when one element is nested inside a second element, and both elements have registered a listener for the same event (a click, for example). With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.

With capturing, the event is first captured by the outermost element and propagated to the inner elements.

Let's look at examples of both.

For both of the following examples, create the following HTML −

Example

<div id='outer' style='background-color:red;display:inline-block;padding:50px;'>
   Outer Div
   <div id='inner' style='background-color:yellow;display:inline-block;padding:50px;'>
      Inner Div
   </div>
</div>

Event Bubbling

document.querySelector('#outer').addEventListener('click', e => {
   console.log('Outer div is clicked');
}, false);
document.querySelector('#inner').addEventListener('click', e => {
   console.log('Inner div is clicked');
}, false);

If you run the above code and click in the inner div, you'll get the log −

Inner div is clicked

Outer div is clicked

Event Capturing

document.querySelector('#outer').addEventListener('click', e => {
   console.log('Outer div is clicked');
}, true);
document.querySelector('#inner').addEventListener('click', e => {
   console.log('Inner div is clicked');
}, true);

Output

If you run the above code and click in the inner div, you'll get the log −

Outer div is clicked
Inner div is clicked

Updated on: 19-Sep-2019

550 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements