Yes! Event propagation in the HTML DOM determines the order in which event handlers are triggered when an event occurs on a nested element. There are two phases of event propagation:
1. Event Bubbling (Default)
- In event bubbling, the event starts from the innermost element that was clicked and then bubbles up to its ancestors.
- This means that the event is first handled by the targeted element, then moves up to its parent, then grandparent, and so on.
component3 → component2 → component1
2. Event Capturing (Trickling)
- In event capturing, the event starts from the outermost ancestor and trickles down to the target element.
- This phase is less commonly used but can be explicitly enabled.
component1 → component2 → component3
Example Code
Here’s a simple example using event listeners in both bubbling and capturing phases:
<div id="component1" style="padding: 20px; background-color: lightblue;">
Component 1
<div id="component2" style="padding: 20px; background-color: lightgreen;">
Component 2
<div id="component3" style="padding: 20px; background-color: lightcoral;">
Component 3 (Click here)
</div>
</div>
</div>
<script>
document.getElementById("component1").addEventListener("click", function() {
console.log("Component 1 clicked");
}, false); // false -> Bubbling Phase
document.getElementById("component2").addEventListener("click", function() {
console.log("Component 2 clicked");
}, false);
document.getElementById("component3").addEventListener("click", function() {
console.log("Component 3 clicked");
}, false);
</script>
How to Use Capturing Phase?
If you want to enable event capturing, pass true
as the third argument:
document.getElementById("component1").addEventListener("click", function() {
console.log("Component 1 clicked");
}, true); // true -> Capturing Phase
Stopping Event Propagation
You can use event.stopPropagation()
to prevent the event from propagating further:
document.getElementById("component3").addEventListener("click", function(event) {
console.log("Component 3 clicked");
event.stopPropagation(); // Stops event bubbling or capturing
});