stopPropagation vs stopImmediatePropagation

This demo demonstrate the differences between stopPropagation and stopImmediatePropagation.

by Lavakumar T

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>

<div class="container">
    <a href="#" class="item element">Click Me!</a>
</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.
$('.item').on('click', function(e) {
    console.log('an item was clicked');
});

$('.element').on('click', function(e) {
    e.preventDefault(); // Now link won't go anywhere
    e.stopPropagation(); // Now the event won't bubble up
    console.log('element was clicked');
});
var button = document.getElementById("b");
button.addEventListener("click", function (e) {
    console.log("e1");
e.stopPropagation();
    //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.
});