Sawyer
Sawyer

Reputation: 15917

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.

Upvotes: 2

Views: 2207

Answers (3)

Arun
Arun

Reputation: 142

Unbind and bind the function.

bindEvent();
function bindEvent(){
    $(".remove").unbind("click");
    $(".remove").bind("click",function() {
        $(this).remove();
        bindEvent();
    });
    $(".add").unbind("click");
    $(".add").bind("click", function() {
     $(this).clone().toggleClass("add remove").text("remove").appendTo($("body"));
        bindEvent();
    });
}

jsfiddle

Upvotes: 0

bhavya_w
bhavya_w

Reputation: 10077

"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.

Upvotes: 1

Vigneswaran Marimuthu
Vigneswaran Marimuthu

Reputation: 2532

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>

Upvotes: 11

Related Questions