0

I'd like to run a function just before a <div> element is removed from document. What eventListener can I add to the <div> element?

If there's no exact event to do it, then how can I bind a function to the <div> element when it's going to be removed? I tried the below, but they didn't work

$('#divToRemove').on('beforeunload', handler);
divToRemove.addEventListener('onbeforeunload', handler);

Any answer will be very appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Benjamin
  • 707
  • 3
  • 8
  • 28
  • 7
    No, unless you raise one manually. You could also use a `MutationObserver` on a parent element, but that won't work in legacy browsers – Rory McCrossan Dec 06 '16 at 13:41
  • The following resources might be interesting to read: https://davidwalsh.name/mutationobserver-api | https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver | http://caniuse.com/#feat=mutationobserver – Flyer53 Dec 06 '16 at 13:58
  • Thank you guys for the answers. very interesting! – Benjamin Dec 06 '16 at 14:45
  • Does this answer your question? [Detect that given element has been removed from the DOM without sacrificing performance](https://stackoverflow.com/questions/50391422/detect-that-given-element-has-been-removed-from-the-dom-without-sacrificing-perf) – phuzi Jul 23 '21 at 10:40

1 Answers1

0

You can use jQuery UI's on() method to handle the removal of an event like this:

$("#divToRemove").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/

Hope this helps!

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
  • Would you please post a link to the documentation of a jQuery UI `.on()` method. This would have to be a method override of the jQuery method. But such an override is not listed in the jQuery UI docs. Nor does it appear in the listing of jQuery UI methods. (I checked only the current jQuery UI version 1.12.1) – Flyer53 Dec 06 '16 at 14:10
  • I'm sure this could be a solution, but this doesn't work. I'm working with React.js so all of view are React component. Do you know what event happens when a component is unmounting to the elements in the component? – Benjamin Dec 06 '16 at 14:43