0

I have a node: <div id = "box1" class = "box center green size200"></div>

I have this event handler:

document.body.addEventListener("click", function(event) {

figureObject.createOutline(event.target);

});

I also have a function in a figureObject called createOutline which looks like this: (ifOutline is a variable in the object which keeps track if the figure is selected or not(outlined).

if(this.ifOutlined == false) { 

elem.classList.add('selected');

this.ifOutlined = true;

} else if(this.ifOutlined == true) {

elem.classList.remove('selected');

this.ifOutlined = false;

}

Then i have a css selector that looks like this:

.selected {border: 2px solid black;}

I duplicate the box1 element(which is the original element on the screen) using:

var clone = box1.cloneNode();
var parent = clone.parentNode;
parent.appendChild(clone);

The event handler works fine on the first figure that is on the screen(a green square). But the clone that is created after the duplication will not respond to the event handler, why does this happen?

  • Possible duplicate of [Clone element with all its events](http://stackoverflow.com/questions/16939335/clone-element-with-all-its-events) – markasoftware Nov 24 '15 at 17:44
  • I want to know why it doesn't work, thank you for showing me another way of doing it though. – Daniel Abella Nov 24 '15 at 17:49
  • It doesn't work because the event handler is not part of the node itself, and cloneNode just clones the node – markasoftware Nov 24 '15 at 17:50
  • No but it is part of the body element which contains the cloned node. – Daniel Abella Nov 24 '15 at 17:52
  • I also tried writing a function addEventListenerToNode(whichNode) { whichNode.addEventListener("click",function() { figureObject.createOutline(whichNode); }); } This also did not work, which make me think it's not possible to add event listeners to clones. Can you explain it perhaps? – Daniel Abella Nov 24 '15 at 18:08

0 Answers0