6

What is the core javascript equivelent to the jquery's remove event listener

$(element).on('remove', someFunction);

Snaker.Wood
  • 609
  • 2
  • 7
  • 13
  • Have you tried `element.addEventListener("remove", someFunction)`? – Niccolò Campolungo Sep 27 '13 at 12:30
  • @LightStyle—you may need to [check the spec](http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener), there is no "remove" event. – RobG Sep 27 '13 at 12:58
  • @RobG, didn't check the spec because I hadn't time to do it. I simply guessed, and I was wrong. ;) – Niccolò Campolungo Sep 27 '13 at 15:46
  • 1
    I actually found the following: `code` element.addEventListener("DOMNodeRemoved", someFunction); `code` – Snaker.Wood Sep 27 '13 at 16:47
  • An update to this answer that does use Remove is available here http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom. – crazycharlie Sep 22 '14 at 14:32

2 Answers2

5

There is no such event as remove, either as a DOM standard event or as a jQuery extension. Your example does nothing.

You will be able to use Mutation Observers to look for removedNodes in the future, but browser support isn't there yet.

bobince
  • 528,062
  • 107
  • 651
  • 834
2

Here's how to do it with a Mutation Observer:

function onElementRemoved(element, callback) {
  new MutationObserver(function(mutations) {
    if(!document.body.contains(element)) {
      callback();
      this.disconnect();
    }
  }).observe(element.parentElement, {childList: true});
}

// Example usage: 
onElementRemoved(yourElement, function() {
  console.log("yourElement was removed!");
});
joe
  • 3,752
  • 1
  • 32
  • 41