In JavaScript, event propagation involves two phases: capturing phase and bubbling phase. These phases determine the order in which event handlers are triggered when an event occurs on a nested DOM element. Let’s explore each phase with an example:
Bubbling Phase: In the bubbling phase, an event starts from the target element that triggered the event and then bubbles up through its parent elements in the DOM tree. The event handlers of the parent elements are called in order from the target element to the root of the document.
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="outer">
<div id="middle">
<div id="inner">Click me!</div>
</div>
</div>
<script>
document.getElementById('outer').addEventListener('click', () => {
console.log('Outer Div Clicked');
});
document.getElementById('middle').addEventListener('click', () => {
console.log('Middle Div Clicked');
});
document.getElementById('inner').addEventListener('click', () => {
console.log('Inner Div Clicked');
});
</script>
</body>
</html>
If you click on the “Inner Div,” you’ll see the following output in the console:
Inner Div Clicked
Middle Div Clicked
Outer Div Clicked
This is because the click event first triggers on the innermost element and then bubbles up to the outer elements in the order of nesting.
Capturing Phase: In the capturing phase, the event travels down the DOM tree from the root element to the target element. This phase is less commonly used than the bubbling phase.
document.getElementById('outer').addEventListener('click', () => {
console.log('Outer Div Clicked - Capturing');
}, true); // true indicates capturing phase
document.getElementById('middle').addEventListener('click', () => {
console.log('Middle Div Clicked - Capturing');
}, true);
document.getElementById('inner').addEventListener('click', () => {
console.log('Inner Div Clicked - Capturing');
}, true);
With the capturing phase handlers in place, clicking the “Inner Div” will produce this output:
Outer Div Clicked - Capturing
Middle Div Clicked - Capturing
Inner Div Clicked - Capturing
The capturing phase can be set by passing true
as the third argument to the addEventListener
function. By default, event listeners are in the bubbling phase.
Both bubbling and capturing phases are part of the event propagation model in the DOM, and understanding them helps you control how events are handled in your web applications.