PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 16, 2022

[FIXED] How do I attach a listener to a cloned element?

 October 16, 2022     dom, dom-events, javascript     No comments   

Issue

I'm currently learning about DOMs and have this problem I'm struggling with when two or more cloned elements get 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

box 1 is the original box and it has its own EventListener.

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

box 3-4 are clones of 1-2 but it seems that box 3 and 4 get the same listener because when I click on box 4 it toggles selected on box 3 and nothing happens with box 4.

How do I solve this?

Any help will be most welcome.


Solution

I think this is a scoping issue. Your event handler is making reference to node, but at the end of the loop, node will point to the last square created. You can store the value of node for each event handler using a closure:

(function(node) {

    // 'node' defined here is in it's 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 better solution is to use this within your event handler:

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

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


Answered By - Ben Jackson
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing