stopPropagation vs stopImmediatePropagation
This demo demonstrate the differences between stopPropagation and stopImmediatePropagation.
by cmd0
HTML
<div id="gray" class="gray">just a blue block</div>
<input type="button" value="click" id="b" />
<div id="div1">this is div1
<p id="p1">this is p1.</p>
</div>
CSS
.gray {
background-color: gray;
width: 50px;
height: 100px;
padding: 1em 1em 1em 1em;
}
JavaScript
//differences between stopPropagation and stopImmediatePropagation.
//the keyword for stopPropagation is parent.
//the keyword for stopImmediatePropagation is other events of the element.
var button = document.getElementById("b");
button.addEventListener("click", function (e) {
console.log("e1");
e.stopImmediatePropagation(); // this prevents the 2nd event for button to fire.
});
button.addEventListener("click", function (e) {
console.log("e2");
});
var d1 = document.getElementById("div1");
var p1 = document.getElementById("p1");
d1.addEventListener("click", function (e) {
console.log("d1");
});
p1.addEventListener("click", function (e) {
console.log("p1");
//e.stopPropagation(); // This prevents the parent event from firing.
});