Alex Rivera | Logout

jQuery: Any way to "refresh" event handlers?

Asked 2010-05-25T21:54:28.913
16

I have two divs, one that holds some stuff and the other with all possible stuff. Clicking on one of the divs will transfer items to the other div. The code I came up with is:

$("#holder > *").each(function() {
    $(this).click(function(e) {
        $(this).remove();
        $("#bucket").append(this);
    });
});

$("#bucket > *").each(function() {
    $(this).click(function(e) {
        $(this).remove();
        $("#holder").append(this);
        });
});

This one works perfectly, except that the event handlers need to be refreshed once I append or remove elements. What I mean is, if I first click on an element, it gets added to the other div, but if I click on this element again, nothing happens. I can do this manually but is there a better way to achieve this?

Edit
Report

1 Answer

24

Try jquery live events .. the $.live(eventname, function) will bind to any current elements that match as well as elements added to the Dom in the future by javascript manipulation.

example:

$("#holder > *").live("click", function(e) { 
        $(this).remove(); 
        $("#bucket").append(this); 
}); 

$("#bucket > *").live("click", function(e) { 
        $(this).remove(); 
        $("#holder").append(this); 
});

Important:

Note that $.live has since been stripped from jQuery (1.9 onwards) and that you should instead use $.on.

I suggest that you refer to this answer for an updated example.

answered 2010-05-25T21:57:53.357

Your Answer