Computer >> Computer tutorials >  >> Programming >> Javascript

What is event Bubbling and capturing in JavaScript?


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>

1. 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

2. 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);

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