jQuery - Trigger event when an element is removed from the DOM

sa125 picture sa125 · Feb 4, 2010 · Viewed 149.6k times · Source

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.

Answer

mtkopone picture mtkopone · Apr 16, 2012

You can use jQuery special events for this.

In all simplicity,

Setup:

(function($){
  $.event.special.destroyed = {
    remove: function(o) {
      if (o.handler) {
        o.handler()
      }
    }
  }
})(jQuery)

Usage:

$('.thing').bind('destroyed', function() {
  // do stuff
})

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') { ... }