Question

My question is, why isn't the click event on the third div triggered anymore, after i've detached the elements and appended them back? The events aren't preserved.

var test = (function($, undef) {
    var t = {};
    t.test = function(){
        var container = $('<div/>').appendTo('body');           
        $('<div/>', {
            'class' :   'some',
            'text'  :   'text'
        }).appendTo(container);         
        $('<div/>', {
            'class' :   'some',
            'text'  :   'text'
        }).appendTo(container);         
        $('<div/>', {
            'class' :   'some',
            'text'  :   'text',
            'click' :   function(){
                console.log("ahoy");
            }
        }).appendTo(container);         
        $('<div/>', {
            'class' :   'some',
            'text'  :   'text'
        }).appendTo(container);         
        var content = container.html();
        var detachedContent = $(content).detach();
        container.empty();          
        //setTimeout(function(){
            container.append(detachedContent);
        //}, 2000);         
    };      
    return t;
})(jQuery); 
test.test();

example: http://jsfiddle.net/sCJfc/

Was it helpful?

Solution

detach() is not to blame here.

You're performing a copy of the container element's inner markup, and you're detaching the elements created from that copy. These elements are not part of the DOM to begin with, and will indeed not have any handler registered on them.

Try writing:

var detachedContent = container.children().detach();

Instead of:

var content = container.html();
var detachedContent = $(content).detach();

OTHER TIPS

Try cloning the child elements, removing them and then adding them back using the clone.

var detachedContent = $(container).children().clone(true);
console.log(detachedContent);
container.empty();

container.append(detachedContent);

Working Example: http://jsfiddle.net/sCJfc/2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top