event delegation in js

by bhupendra negi

HTML

<div id="container">Container
    <div id="parent">Parent
        <div id="child">Child</div>
    </div>
</div>

CSS

div {
    position:absolute;
    cursor:pointer;
}
#container {
    width:200px;
    height:200px;
    background-color:blue;
    color:white
}
#parent {
    width:100px;
    height:100px;
    top:50px;
    left:50px;
    background-color:yellow;
    color:black;
}
#child {
    width:50px;
    height:50px;
    top:30px;
    left:20px;
    background-color:red;
}

JavaScript

function main() {
    var box = document.getElementById("container");
    //attach click on individualbox
    //   box.addEventListener('click',test,false);

    //propogating events 
    box.addEventListener('click', propogate, false)

    //traditional way of attaching event
    /* document.getElementById("parent").onclick = function(event){
    alert("parent traditional");
};
    */


}

function test(e) {
    var el = e.target;
    console.log(el.id);

}

function propogate(e) {
    console.log("EVENT BUBBLING..");
    var el = e.target;
    while (el != document) {
        console.log(el.id);
        el = el.parentNode;
    }

}

window.onload = main()
/*benefits
1. less functions to manage
2. takes up less memory
3. works for dynamically generated elements



*/