jQuery clone keep events

Have you ever used jQuery’s clone function and lost event handlers on the new element? Learn how to keep the handlers by using the code in this article.

HTML

<div>
    <a href="#">Click me</a>
</div>

JavaScript

Problem

Using the code below will cause your event handlers to be lost when you use jQuery’s clone function. If you switch the order of the JavaScript so that you clone the element first and then apply the handler, the code will work just fine. I suggest that you don’t tinker with the order because it could cause you a lot trouble in the future and the best solution is to use the live, delegate and on function shown at the bottom of the article.

$(document).ready(function(){
    //Handler will not be on cloned element 
    $('a').click(function(){
        $(this).after('<p>Clicked</p>');
    })

    $('div').after($('div').clone());  
});

Solution

The live, delegate and on functions are the best way to preserve your event handlers when you use the clone function. Each function is more efficient than the last so make sure to use the most recent function supported by your version of jQuery.

$(document).ready(function(){
    //jQuery 1.3+ 
    $('a').live('click', function(){
        $(this).after('<p>Clicked</p>');
    });

    //jQuery 1.4.3+ 
    $(document).delegate("a", "click", function(){ 
        $(this).after('<p>Clicked</p>');
    });

    //jQuery 1.7+ 
    $(document).on("click", "a", function(){ 
        $(this).after('<p>Clicked</p>');
    })

    $('div').after($('div').clone());  
});