How do I connect a listener to a cloned element?

I am currently researching the DOM and have this problem that I am struggling with where two or more cloned elements receive the same event listener.

        case 116:
            var myList = document.querySelectorAll(".selected");
            for(var i=0; i<myList.length;i++)
            {
                var node=myList[i].cloneNode(true);
                node.style.top=Math.random()*window.innerHeight-(node.style.height/2)+"px";
                node.style.left=Math.random()*window.innerWidth-(node.style.width/2)+"px";
                node.addEventListener("click",function(e){
                    node.classList.toggle("selected");
                    console.log(e);
                });
                myList[i].parentNode.appendChild(node);
            }
            break;

      

the code

field 1 is the original field and has its own EventListener.

field 2 is a clone of the original and selects and deselects as it should.

box 3-4 are clones of 1-2, but it seems that the same listener appears in box 3 and 4, because when I click on box 4 it switches to box 3 and nothing happens to box 4.

How to solve this?

Any help would be greatly appreciated.

+3


source to share


1 answer


I think this is the problem. The event handler references node

but at the end of the loop node

will point to the last square created. You can store a value node

for each event handler using a closure:

(function(node) {

    // 'node' defined here is in it own scope, so won't be affected by the changes
    // made to the 'node' variable defined in the outer scope of the loop.
    node.addEventListener("click",function(e){
        node.classList.toggle("selected");
        console.log(e);
    });

})(node);

      



but probably the best solution is to use this

in your event handler:

node.addEventListener("click",function(e){

    // within an event handler, 'this' references the event target element
    this.classList.toggle("selected");
    console.log(e);
});

      

+1


source







All Articles