Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending element and removing it destroys all event handlers in jquery?

Ok I create element, assign click handler, and append it to body. Then i remove it and reappend it and click handler is no longer working???

Why would this happen.

var btn = $('<button>').text('hi').click(function(){console.log(3);});
var div = $('<div>');
div.append(btn);
$('body').append(div);
//click it now, it works..
div.html('');
div.append(btn);
// now button doesn't work..

So why is this happening and what can i do to fix it.

like image 230
Muhammad Umer Avatar asked Apr 05 '15 20:04

Muhammad Umer


People also ask

Does removing an element remove event listeners?

In modern browsers, if a DOM Element is removed, its listeners are also removed from memory in javascript. Note that this will happen ONLY if the element is reference-free. Or in other words, it doesn't have any reference and can be garbage collected. Only then its event listeners will be removed from memory.

Does jQuery empty Remove event handlers?

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

Which event is removed in jQuery?

jQuery unbind() Method The unbind() method removes event handlers from selected 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.


1 Answers

Since .html('') is essentially the same as .empty(), the following applies (from the jQuery docs):

To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.

If you want to remove elements without destroying their data or event handlers (so they can be re-added later), use .detach() instead.

One option would be to use event delegation. In doing so, the event isn't bound directly to the button element, it is bound to a constant parent element that isn't removed.

Example Here

$(document).on('click', 'button', function () {
    // ..
});

As mentioned above, another option would be to use the .detach() method in order to remove the element from the DOM, without removing attached event listeners.

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

Example Here

div.find('button').detach();
div.append(btn);
like image 171
Josh Crozier Avatar answered Oct 12 '22 23:10

Josh Crozier