Event bubbling and capturing
Event bubbling and capturing are two ways of event propagation in the HTML DOM API, when an event occurs in an element inside another element, and both elements have registered a handle for that event. The event propagation mode determines in which order the elements receive the event.
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.
Capturing is also called “trickling“, which helps remember the propagation order:
The following is the syntax of Event bubbling and capturing −
addEventListener(type, listener, useCapture)
Parameters
- type− Used to refer to the type of event.
- listener− The function which we want to call when the event of the particular type occurs.
- userCapture− it is a Boolean value. It indicates the event phase. It will be false by default and that indicates it is in the bubbling phase.
Event capturing
When you use event capturing
| |
---------------| |-----------------
| element1 | | |
| -----------| |----------- |
| |element2 \ / | |
| ------------------------- |
| Event CAPTURING |
-----------------------------------
the event handler of element1 fires first, the event handler of element2 fires last.
Event bubbling
When you use event bubbling
/ \
---------------| |-----------------
| element1 | | |
| -----------| |----------- |
| |element2 | | | |
| ------------------------- |
| Event BUBBLING |
-----------------------------------
the event handler of element2 fires first, the event handler of element1 fires last.
[ You might also like: JavaScript Interview Questions for 5+ Years Experience ]
Let’s look at examples of both.
For both of the following examples, create the following HTML −
Example
<div id='outer-div' style='background-color:green;display:inline-block;padding:50px;'> Outer Div <div id='inner-div' style='background-color:red;display:inline-block;padding:50px;'> Inner Div </div> </div>
1. Event Bubbling
document.querySelector('#outer-div').addEventListener('click', e => { console.log('Outer div is clicked'); }, false); document.querySelector('#inner-div').addEventListener('click', e => { console.log('Inner div is clicked'); }, false);
Inner div is clicked Outer div is clicked
2. Event Capturing
document.querySelector('#outer-div').addEventListener('click', e => { console.log('Outer div is clicked'); }, true); document.querySelector('#inner-div').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