xxxxxxxxxx
<!---- stopImmediatePropagation() vs stopPropagation() ----------------->
`stopPropagation` allows other event handlers on the SAME ELEMENT
on the SAME EVENT to be executed, while `stopImmediatePropagation`
prevents this.
<script>
el.addEventListener( "click", e => e.stopImmediatePropagation() )
el.addEventListener( "click", e => console.log("This will not run.") )
</script>
<!----------------- stopImmediatePropagation() vs stopPropagation() ---->
xxxxxxxxxx
<!DOCTYPE html>
<html>
<head>
<title>Event Propagation Example with stopPropagation()</title>
</head>
<body>
<div id="outer">
<div id="middle">
<div id="inner">
<button id="btn">Click Me!</button>
</div>
</div>
</div>
<script>
// Event handler for the outer div
function outerHandler() {
console.log("Outer div clicked!");
}
// Event handler for the middle div
function middleHandler(event) {
console.log("Middle div clicked!");
event.stopPropagation(); // Stop propagation here
}
// Event handler for the inner div
function innerHandler(event) {
console.log("Inner div clicked!");
event.stopPropagation(); // Stop propagation here
}
// Event handler for the button
function buttonHandler() {
console.log("Button clicked!");
}
// Add event listeners to the elements
document.getElementById("outer").addEventListener("click", outerHandler);
document.getElementById("middle").addEventListener("click", middleHandler);
document.getElementById("inner").addEventListener("click", innerHandler);
document.getElementById("btn").addEventListener("click", buttonHandler);
</script>
</body>
</html>
xxxxxxxxxx
<!-- index.html -->
<div id="credit">Procrastination for Dummies</div>
Copy code
JAVASCRIPT
/* script.js */
const credit = document.querySelector("#credit");
credit.addEventListener("click", function(event) {
console.log("Nah, I'll do it later");
});
credit.addEventListener("click", function(event) {
console.log("I WILL do it tomorrow");
event.stopImmediatePropagation();
});
credit.addEventListener("click", function(event) {
console.log("Why do I have so much work piled up?!");
});
/* Clicking on the div block will print to the console:
Nah, I'll do it later
I WILL do it tomorrow
*/