Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are events lost in jQuery when you remove() an element and append() it elsewhere?

Tags:

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.

like image 531
Simon_Weaver Avatar asked Feb 17 '09 23:02

Simon_Weaver


People also ask

Are event listeners removed when element is removed?

According to the jquery Documentation when using remove() method over an element, all event listeners are removed from memory. This affects the element it selft and all child nodes. If you want to keep the event listners in memory you should use . detach() instead.

What is the difference between remove () and detach () methods in jQuery?

remove() removes the matched elements from the DOM completely. detach() is like remove() , but keeps the stored data and events associated with the matched elements.

How remove and append in jQuery?

jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.

Is jQuery can be used to both add and remove DOM elements?

Yes, it's so we can easily remove each input individually.


2 Answers

The jQuery detach() function is the same as remove() but preserves the event handlers in the object that it returns. If you have to remove the item and place it somewhere else with everything you can just use this.

var objectWithEvents = $('#old').detach(); $('#new').append(objectWithEvents); 

Check the API docs here: http://api.jquery.com/detach/

like image 78
BrutalDev Avatar answered Mar 29 '23 11:03

BrutalDev


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.

like image 34
Crescent Fresh Avatar answered Mar 29 '23 10:03

Crescent Fresh