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
an extension to Adam's answer incase you need to prevend default, here is a work around:
$(document).on('DOMNodeRemoved', function(e){
if($(e.target).hasClass('my-elm') && !e.target.hasAttribute('is-clone')){
let clone = $(e.target).clone();
$(clone).attr('is-clone', ''); //allows the clone to be removed without triggering the function again
//you can do stuff to clone here (ex: add a fade animation)
$(clone).insertAfter(e.target);
setTimeout(() => {
//optional remove clone after 1 second
$(clone).remove();
}, 1000);
}
});
For those who use jQuery UI:
jQuery UI has overridden some of the jQuery methods to implement a remove
event that gets handled not only when you explicitly remove the given element, but also if the element gets removed from the DOM by any self-cleaning jQuery methods (e.g. replace
, html
, etc.). This basically allows you to put a hook into the same events that get fired when jQuery is "cleaning up" the events and data associated with a DOM element.
John Resig has indicated that he's open to the idea of implementing this event in a future version of jQuery core, but I'm not sure where it stands currently.
Just checked, it is already built-in in current version of JQuery:
jQuery - v1.9.1
jQuery UI - v1.10.2
$("#myDiv").on("remove", function () {
alert("Element was removed");
})
Important: This is functionality of Jquery UI script (not JQuery), so you have to load both scripts (jquery and jquery-ui) to make it work. Here is example: http://jsfiddle.net/72RTz/
I'm not sure there is an event handle for this, so you would have to keep a copy of the DOM and compare to the existing DOM in some kind of polling loop - which could be quite nasty. Firebug does this though - if you inspect the HTML and run some DOM-changes, it highlights the changes in yellow in the Firebug console for a short time.
Alternatively, you could create a remove function...
var removeElements = function(selector) {
var elems = jQuery(selector);
// Your code to notify the removal of the element here...
alert(elems.length + " elements removed");
jQuery(selector).remove();
};
// Sample usage
removeElements("#some-element");
removeElements("p");
removeElements(".myclass");
There is no built-in event for removing elements, but you can create one by fake-extending jQuery's default remove method. Note that the callback must be called before actually removing it to keep reference.
(function() {
var ev = new $.Event('remove'),
orig = $.fn.remove;
$.fn.remove = function() {
$(this).trigger(ev);
return orig.apply(this, arguments);
}
})();
$('#some-element').bind('remove', function() {
console.log('removed!');
// do pre-mortem stuff here
// 'this' is still a reference to the element, before removing it
});
// some other js code here [...]
$('#some-element').remove();
Note: some problems with this answer have been outlined by other posters.
html()
replace()
or other jQuery methodsThe most elegant solution to this problem seems to be: https://stackoverflow.com/a/10172676/216941
(I have extracted this extension from the jQuery UI framework)
Works with: empty()
and html()
and remove()
$.cleanData = ( function( orig ) {
return function( elems ) {
var events, elem, i;
for ( i = 0; ( elem = elems[ i ] ) != null; i++ ) {
try {
// Only trigger remove when necessary to save time
events = $._data( elem, "events" );
if ( events && events.remove ) {
$( elem ).triggerHandler( "remove" );
}
// Http://bugs.jquery.com/ticket/8235
} catch ( e ) {}
}
orig( elems );
};
} )( $.cleanData );
With this solution you can also unbind the event handler.
$("YourElemSelector").off("remove");
Try it! - Example
$.cleanData = (function(orig) {
return function(elems) {
var events, elem, i;
for (i = 0;
(elem = elems[i]) != null; i++) {
try {
// Only trigger remove when necessary to save time
events = $._data(elem, "events");
if (events && events.remove) {
$(elem).triggerHandler("remove");
}
// Http://bugs.jquery.com/ticket/8235
} catch (e) {}
}
orig(elems);
};
})($.cleanData);
$("#DivToBeRemoved").on("remove", function() {
console.log("div was removed event fired");
});
$("p").on("remove", function() {
console.log("p was removed event fired");
});
$("span").on("remove", function() {
console.log("span was removed event fired");
});
// $("span").off("remove");
$("#DivToBeRemoved").on("click", function() {
console.log("Div was clicked");
});
function RemoveDiv() {
// $("#DivToBeRemoved").parent().html("");
$("#DivToBeRemoved").remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>OnRemove event handler attached to elements `div`, `p` and `span`.</h3>
<div class="container">
<br>
<button onclick="RemoveDiv();">Click here to remove div below</button>
<div id="DivToBeRemoved">
DIV TO BE REMOVED
contains 1 p element
which in turn contains a span element
<p>i am p (within div)
<br><br><span>i am span (within div)</span></p>
</div>
</div>
Additional Demo - jsBin