1

I am trying to clone a div which has input fields. But the eventListeners are not being fired.

Even though I am doing a deep clone in the following way -

var rows = document.querySelectorAll('.row');
var dupNode = rows[0].cloneNode(true);
sheet.appendChild(dupNode);

Here is the Demo

Each input has a click event and the cloned inputs are not registering with the click event. What am I missing ?

Ajey
  • 7,924
  • 12
  • 62
  • 86

2 Answers2

1

The simplest (and the most effective) thing to do is to bind single event listener on the #sheet container and benefit from event bubbling. In this case you can append as many new elements as you wish and will never need to bind events to them:

document.querySelector('#sheet').addEventListener('click', function(e) {
    var target = e.target;
    if (target.tagName == 'INPUT') {
        alert("clicked");
    }
}, false);

A little tricky part is that you need to check on what element event occurred and execute your code on those only you are interested in.

Demo: http://jsbin.com/mejegaqasu/1/edit?html,js,output

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • One thing to watch for: this only works for events that bubble, and not all of them do. Some, like focus and blur, aren't supposed to bubble according to the standard, but some browsers have bugs. The change event is especially painful if you have to work in IE8 and under, because it doesn't bubble there (even though it should). – The Spooniest Dec 31 '14 at 14:21
0

Event handlers are not copied during cloning. You will need to delegate the event handlers if you want them to work everywhere in the DOM after cloning.

Event delegation http://davidwalsh.name/event-delegate cloneNode documentation https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode

unobf
  • 7,158
  • 1
  • 23
  • 36