views:

1028

answers:

2

What happens in jQuery when you remove() an element and append() it elsewhere?

It appears that the events are unhooked - as if you were just inserting fresh html (which I guess is what happening). But its also possible my code has a bug in it - so I just wanted to verify this behavior before I continue.

If this is the case - are there any easy ways to rehookup the events to just that portion of HTML, or a different way to move the element without losing the event in the first place.

A: 

use jQuery1.3.1 live() to bind events and you won't need to worry about this..

Scott Evernden
so yes to my original question? what exactly happens. i'll check into 'live' now
Simon_Weaver
definitely good to know about live - but got to be careful of the caveats here http://docs.jquery.com/Events/live#typefn
Simon_Weaver
+1  A: 

Yes, jQuery's approach with remove() is to unbind everything bound with jQuery's own bind (to prevent memory leaks).

However, if you just want to move something in the DOM, you don't have to remove() it first. Just append to your heart's content, the event bindings will stick around :)

For example, paste this into your firebug on this page:

$('li.wmd-button:eq(2)').click(function(){ alert('still here!') }).appendTo(document.body)

And now scroll down to the bottom of this page and click on the little globy icon now buried under the SO footer. You will get the alert. All because I took care to not remove it first.

Crescent Fresh
cool. i was hoping something like that was the case. yay for interactive stackoverflow !
Simon_Weaver