event propogation

event propogation example

by karthick6891

HTML

<div class="d1">1
    <!-- the topmost -->
    <div class="d2">2
        <div class="d3">3
            <!-- the innermost -->
        </div>
    </div>
</div>

CSS

.d1 {
    background-color: green;
    position: relative;
    width: 150px;
    height: 150px;
    text-align: center;
    cursor: pointer;
}
.d2 {
    background-color: blue;
    position: absolute;
    top: 25px;
    left: 25px;
    width: 100px;
    height: 100px;
}
.d3 {
    background-color: red;
    position: absolute;
    top: 25px;
    left: 25px;
    width: 50px;
    height: 50px;
    line-height: 50px;
}

JavaScript

var divs = document.getElementsByTagName('div')

for (var i = 0; i < divs.length; i++) {
    divs[i].onclick = function (e) {
        e = e || event;
        var target = e.target || e.srcElement;
        e.preventDefault();
        if (e.stopPropagation) {
            // W3C standard variant
            e.stopPropagation()
        } else {
            // IE variant
            e.cancelBubble = true
        }
        this.style.backgroundColor = 'yellow';

        console.log("target = " + target.className + ", this=" + this.className);

        this.style.backgroundColor = '';


    }



}