Skip to content Skip to sidebar Skip to footer

Jquery .on() Doesn't Work For Cloned Element

It seems .on() failed to bind newly created element from clone()
add
$('.remove').on('click',functio

Solution 1:

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"));
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><divclass="container"><divclass="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"));
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><divclass="container"><divclass="add">add</div></div>

Solution 2:

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

Solution 3:

Unbind and bind the function.

bindEvent();
functionbindEvent(){
    $(".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

Post a Comment for "Jquery .on() Doesn't Work For Cloned Element"