Event Delegation

by jordwms

HTML

<ul id="my-list">
    <li>One</li>
    <li>Two <a href="#">A link inside</a></li>
    <li>Three</li>
</ul>

JavaScript

var myList = document.getElementById("my-list");

myList.addEventListener("click", function(event) {

    event.preventDefault();
    
    console.group("Event fired");    
    console.log("The event", event);
       
    // "this" references the element that is handling the event (the UL)
    console.log("this", this);
    
    // event.currentTarget references the element that is handling the event
    // event.currentTarget === this; in this case
    
    this.style.color="#FF9900";
    // same as
    //event.currentTarget.style.color="#FF9900";

    // event.target references the element that triggered the event (the li)
    // take note! the "highest" element will source the event
    // in this case, the <a> inside the <li> will be the target at times
    console.log("event.target", event.target);
        
    // to delegate, we check from where the event came
    // and handle it as we please    
    if (event.target && event.target.nodeName == "LI") {
        // List item found!  Output the ID!
        console.log("List item ", event.target.innerText, " was clicked!");
        //event.target.style.color="#FF9900";
    }
    
    console.groupEnd();
    
});