0

https://jsfiddle.net/d6rsq426/

For some reason, if i add one clone, both of them have different listeners and work separately. If i duplicate (using the t-button) the two clones that now exist so there's 4. The 4th clone works great, but the 3rd listener controls the 4th clone. I've tried to figure out for quite a while but can't find the reason. See the Fiddle. This function in the object is most likely where the problem is.

duplicateSelected()
  • This was what @Bergi was talking about in your previous question. http://stackoverflow.com/questions/33942679/eventlistener-will-not-work-on-clones/33943007?noredirect=1#comment55645254_33943007 – Arg0n Nov 26 '15 at 18:20
  • @SébastienRenauld Not the IDs, the "Same clone in all eventlisteners"-thingy. Look at question comments. – Arg0n Nov 26 '15 at 18:23
  • @Arg0n: Ah, that. Removing my comment! – Sébastien Renauld Nov 26 '15 at 18:28

1 Answers1

0

Do something like this:

var whichSelected = document.querySelectorAll(".selected");

for(var i = 0; i < whichSelected.length; i++) {
    var clone = whichSelected[i].cloneNode(false);
    (function(clone){
        clone.addEventListener("click", function() {createOutline(clone)});
    })(clone);
    document.body.appendChild(clone);
}

I have updated your JSFiddle to make this work.

The reason behind this, is that when the eventlistener is called, clone is what it was last in the iteration (for-loop). By using an IIFE (Immidiately invoked function expression), clone is retained when the event fires.

Arg0n
  • 8,283
  • 2
  • 21
  • 38
  • Thank you, you are my personal hero today. So if i understood correctly, the eventListener thinks that the clone that it's suppose to use is the last one that was created by the iterator? This basically means that without the IIFE i can put the eventListener either on top or bottom of the for-loop and it will still be fired only after the for loop has finished iterating and not the order it exists in line-wise? – Daniel Abella Nov 26 '15 at 18:40
  • The click-event happens long after the `for-loop` finishes, yes :). At that time, the variable `clone` might not be what it was when attaching the eventlistener. Please upvote also btw! – Arg0n Nov 26 '15 at 18:42
  • I would love to upvote but i can't because my reputation is still <15. There is still one weird issue with your solution though. If i press duplicate when i have 2 figures on screen, i suddenly get a total of 8 when it should be 4. Any ideas why that may be? – Daniel Abella Nov 26 '15 at 18:55
  • Nope not sure. I figured it out, i changed something else ofc, thank you for your quick response anyway! :) – Daniel Abella Nov 26 '15 at 19:05