Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
101
rated 0 times [  107] [ 6]  / answers: 1 / hits: 43809  / 14 Years ago, tue, may 25, 2010, 12:00:00

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?


More From » jquery

 Answers
35

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.


[#96685] Saturday, May 22, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominics

Total Points: 424
Total Questions: 99
Total Answers: 107

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
dominics questions
Wed, Apr 6, 22, 00:00, 2 Years ago
Thu, Jan 13, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
;