Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Explain the event flow process in Javascript
The JavaScript event flow process describes how events propagate through the DOM tree when an event occurs. This process involves three key phases: capturing, target, and bubbling.
Event Flow Phases
Event Capturing: The event starts from the document root and travels down to the target element.
Event Target: The actual DOM element where the event occurred.
Event Bubbling: The event travels back up from the target element to the document root.
HTML Setup
<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 Example
In bubbling (default behavior), the event starts from the innermost element and propagates upward:
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);
When you click the inner div, the output will be:
Inner div is clicked Outer div is clicked
Event Capturing Example
In capturing, the event starts from the outermost element and travels down to the target:
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);
When you click the inner div, the output will be:
Outer div is clicked Inner div is clicked
Stopping Event Propagation
You can stop the event from propagating using stopPropagation():
document.querySelector('#inner').addEventListener('click', e => {
console.log('Inner div is clicked');
e.stopPropagation(); // Prevents bubbling
}, false);
document.querySelector('#outer').addEventListener('click', e => {
console.log('This will not run');
}, false);
Comparison
| Phase | Direction | addEventListener 3rd Parameter |
|---|---|---|
| Bubbling | Inner ? Outer |
false (default) |
| Capturing | Outer ? Inner | true |
Conclusion
Understanding event flow is crucial for handling complex user interactions. Use capturing for early event interception and bubbling for most common scenarios where child events need to propagate to parents.
