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 from the page
/* need to figure out how to independently detect the above happened */
is there an event tailored for that, something like:
jQuery('#some-element').onremoval( function() {
// do post-mortem stuff here
});
thanks.
referencing to @David answer:
When You want to do soo with another function, eg. html() like in my case, don't forget to add return in new function:
I like mtkopone's answer using jQuery special events, but note that it doesn't work a) when elements are detached instead of removed or b) when some old non-jquery libraries use innerHTML to destroy your elements
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.
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
You can use jQuery special events for this.
In all simplicity,
Setup:
Usage:
Addendum to answer Pierre and DesignerGuy's comments:
To not have the callback fire when calling
$('.thing').off('destroyed')
, change the if condition to:if (o.handler && o.type !== 'destroyed') { ... }
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...
Just checked, it is already built-in in current version of JQuery:
jQuery - v1.9.1
jQuery UI - v1.10.2
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/