Albert Ngo
Albert Ngo

Reputation: 47

addEventListener STILL firing multiple times (even with same name callback)

The below code just applies an event to multiple DOM elements. Since this set of code will be called multiple times, the events will be applied to the same element multiple times.

I avoided having them be assigned again (by using the same callback function instead of anonymous functions), but they are still being applied and fired several times. What am I not seeing here?

//apply delete event listener to all list items
function applyListener(){
    let delBtnS = document.querySelectorAll(".toDoList li span")
    let checkOff = document.querySelectorAll(".toDoList li");

    //separate function won't have event applied multiple times
    let applyCompleted = function(){
        console.log("Apply has been pressed");
    }

    let applyDelete = function(event){
        console.log("Delete has been pressed");
    }

    //checkOff
    for (let item of Array.from(checkOff)){ 
        item.addEventListener("click", applyCompleted);
    }


    //delete button
        for (let btn of Array.from(delBtnS)){
        btn.addEventListener("click", applyDelete);
    }
}

Upvotes: 1

Views: 625

Answers (1)

Vinay
Vinay

Reputation: 7674

It's because event propagates up the DOM tree, means a parent node will react to events even if they happen at it's children. You need to use stopPropagation

let applyDelete = function(event){
    event.stopPropagation(); // click on <span> won't travel to it's parent <li>
    console.log("Delete has been pressed");
}

Upvotes: 1

Related Questions