Snaker.Wood
Snaker.Wood

Reputation: 659

JavaScript: on element removed event listener

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

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

Upvotes: 9

Views: 15462

Answers (2)

joe
joe

Reputation: 5552

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!");
});

Upvotes: 4

bobince
bobince

Reputation: 536389

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.

Upvotes: 5

Related Questions