You must use .clone(true)
as described in the documentation: link
.clone ([withDataAndEvents])
A Boolean that indicates whether event handlers should be copied together with the elements. From jQuery 1.4, the element data will be copied as well.
Example:
var bar = $('.foo .bar');
bar.click(function () {
console.log(Date.now());
});
var clonado = bar.clone(true);
clonado.appendTo('.baz');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h1>Copiado.barde.foopara.baz:</h1><divclass="foo">
Original: <div class="bar">Click em foo</div>
</div>
<hr>
<div class="baz">
Copiado:
</div>
Delegating events
Another way to get the desired result is by delegating events, for example you set .click
to document
, but informs that the expected object is .baz
(example only) and then all elements that are added at any time will have the click event, ie everything from document
, example:
var bar = $('.foo .bar');
//O evento click de document será delegado para todos ".bar"
$(document).on('click', '.bar', function () {
console.log(Date.now());
});
setInterval(function () {
var clonado = bar.clone();
clonado.appendTo('.baz');
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h1>Copiado.barde.foopara.baz:</h1><divclass="foo">
Original: <div class="bar">Click em foo</div>
</div>
<hr>
<div class="baz">
Copiados:
</div>