Click on dynamically generated element does not work

Asked

Viewed 51 times

0

Hi, I am cloning an element via jQuery and when I click on an item of the cloned element click does not work, follow example codes:

Cloning:

var template = $(".products .product.template").clone().prependTo($(".products")).removeClass("template");

Click on the element:

$(".remover").click(function(e) {
    console.log("teste");
    e.stopPropagation();
    return false;
});

This remove class is inside the template of the first code example (cloning).

1 answer

2


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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.