Difference Between StopPropogation and StopImmediatePropagation

by Bharat Sewani

HTML

<div id="parent">
    <div id="child">Click Here to know the difference</div>
</div>

<button id="stopPropagation">Stop Propogation</button>
<button id="stopImmediatePropagation"">Stop Immediate Propogation</button>

CSS

div {
    padding: 1em;
}

#parent {
    background-color: #CCC;
}

#child {
    background-color: #000;
    padding: 5em;
}

button {
    padding: 1em;
    font-size: 1em;
}

.active {
    background-color: green;
    color: white;
}
div {
    padding: 1em;
}

#parent {
    background-color: yellow;
}

#child {
    background-color: #eeeeee;
    padding: 5em;
}

button {
    padding: 1em;
    font-size: 1em;
}

.active {
    background-color: green;
    color: white;
}
div {
    padding: 1em;
}

#parent {
    background-color: #CCC;
}

#child {
    background-color: #eeeeee;
    padding: 5em;
}

button {
    padding: 1em;
    font-size: 1em;
}

.active {
    background-color: green;
    color: white;
}

JavaScript

var state = {
    stopPropagation: false,
    stopImmediatePropagation: false
};

function handlePropagation(event) {
    console.log(event);
    if (state.stopPropagation) {
        event.stopPropagation();
    }
    
    if (state.stopImmediatePropagation) {
        event.stopImmediatePropagation();
    }
}

$("#child").click(function(e) {
    handlePropagation(e);
    alert("First event handler on #child");
});
    
    
$("#child").click(function(e) {
    handlePropagation(e);
    alert("Second event handler on #child");
});

// First this event will fire on the child element, then propogate up and
// fire for the parent element.
$("div").click(function(e) {
    handlePropagation(e);
    alert("Event handler on div: #" + this.id);
});


// Enable/disable propogation
$("button").click(function() {
    var objectId = this.id;
    $(this).toggleClass('active');
    state[objectId] = $(this).hasClass('active');
});