Have to use .clone(true)
as described in the documentation: https://api.jquery.com/clone/
.clone( [withDataAndEvents ] )
A boolean indicating whether event handlers should be copied together with the elements. From jQuery 1.4, the data of the elements will also be copied.
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 .bar de .foo para .baz:</h1>
<div class="foo">
Original: <div class="bar">Click em foo</div>
</div>
<hr>
<div class="baz">
Copiado:
</div>
Delegating events
Another way to achieve the desired result is by delegating events, for example you define the .click
in the document
, but informs that the expected object ("target") is the .baz
(example only) and then all elements that are added at any time will have the click event, ie will be all from the 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 .bar de .foo para .baz:</h1>
<div class="foo">
Original: <div class="bar">Click em foo</div>
</div>
<hr>
<div class="baz">
Copiados:
</div>