Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .on() doesn't work for cloned element

It seems .on() failed to bind newly created element from clone()

<div class="container">
<div class="add">add</div>
</div>


$(".remove").on("click",function() {
    $(this).remove();
});

$(".add").on("click", function() {
 $(this).clone().toggleClass("add remove").text("remove").appendTo($(".container"));
});

jsfiddle

Why this doesn't work?

Update: please note that, I know .clone() takes two parameters, but I don't want to let the cloned element continue registered to the old events, but a new one, I could use .off() and .on() to register again, but my question is why the previously declared .on(".remvove") didn't capture the change in the cloned element.

like image 643
Sawyer Avatar asked Mar 07 '26 14:03

Sawyer


2 Answers

Because you need to pass a boolean parameter to clone so that all data and event handlers will be attached to cloned element.

https://api.jquery.com/clone/

$(".remove").on("click",function() {
    $(this).remove();
});

$(".add").on("click", function() {
 $(this).clone(true).toggleClass("add remove").text("remove").appendTo($(".container"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="add">add</div>
</div>

Edited

$(".container").on("click", '.remove', function() {
    $(this).remove();
});

$(".add").on("click", function() {
 $(this).clone().toggleClass("add remove").text("remove").appendTo($(".container"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="add">add</div>
</div>
like image 157
Vigneswaran Marimuthu Avatar answered Mar 10 '26 05:03

Vigneswaran Marimuthu


"my question is why the previously declared .on(".remvove") didn't capture the change in the cloned element."

Because the event listener was attached to all the elements with class names .remove which existed in the DOM at that point in time.

But with clone you created a new Element. It has just been created. A fresh node. How can your earlier listener work on this.

Solutions:
1.) Either use event delegation and attach your listener to a static ancestor node
2.) Pass the boolean flag while calling the clone function so that your listeners also get copied.
3.) Register the Event Listener Again on that node.

like image 42
bhavya_w Avatar answered Mar 10 '26 04:03

bhavya_w



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!