About Lesson
Stopping Event Propagation
You can stop an event from propagating further using stopPropagation(). This can be useful when you want an event to trigger only on a specific element without bubbling up to ancestors.
Example:
JavaScript
let innerDiv = document.querySelector("#innerDiv");
let outerDiv = document.querySelector("#outerDiv");
innerDiv.addEventListener("click", function(event) {
alert("Inner div clicked!");
event.stopPropagation(); // Stops the event here
});
outerDiv.addEventListener("click", function() {
alert("Outer div clicked!");
});
Clicking innerDiv triggers only its alert because stopPropagation() prevents the event from bubbling up to outerDiv.