I\'m trying to figure out how to execute some js code when an element is removed from the page:
jQuery(\'#some-element\').remove(); // remove some element fr
I couldn't get this answer to work with unbinding (despite the update see here), but was able to figure out a way around it. The answer was to create a 'destroy_proxy' special event that triggered a 'destroyed' event. You put the event listener on both 'destroyed_proxy' and 'destroyed', then when you want to unbind, you just unbind the 'destroyed' event:
var count = 1;
(function ($) {
$.event.special.destroyed_proxy = {
remove: function (o) {
$(this).trigger('destroyed');
}
}
})(jQuery)
$('.remove').on('click', function () {
$(this).parent().remove();
});
$('li').on('destroyed_proxy destroyed', function () {
console.log('Element removed');
if (count > 2) {
$('li').off('destroyed');
console.log('unbinded');
}
count++;
});
Here is a fiddle
This.
$.each(
$('#some-element'),
function(i, item){
item.addEventListener('DOMNodeRemovedFromDocument',
function(e){ console.log('I has been removed'); console.log(e);
})
})
We can also use DOMNodeRemoved:
$("#youridwhichremoved").on("DOMNodeRemoved", function () {
// do stuff
})
This is how to create a jQuery live remove listener:
$(document).on('DOMNodeRemoved', function(e)
{
var $element = $(e.target).find('.element');
if ($element.length)
{
// do anything with $element
}
});
Or:
$(document).on('DOMNodeRemoved', function(e)
{
$(e.target).find('.element').each(function()
{
// do anything with $(this)
}
});
Hooking .remove() is not the best way to handle this as there are many ways to remove elements from the page (e.g. by using .html(), .replace(), etc).
In order to prevent various memory leak hazards, internally jQuery will try to call the function jQuery.cleanData() for each removed element regardless of the method used to remove it.
See this answer for more details: javascript memory leaks
So, for best results, you should hook the cleanData
function, which is exactly what the jquery.event.destroyed plugin does:
http://v3.javascriptmvc.com/jquery/dist/jquery.event.destroyed.js
You can bind to the DOMNodeRemoved event (part of DOM Level 3 WC3 spec).
Works in IE9, latest releases of Firefox and Chrome.
Example:
$(document).bind("DOMNodeRemoved", function(e)
{
alert("Removed: " + e.target.nodeName);
});
You can also get notification when elements are inserting by binding to DOMNodeInserted