Destroy hook when HTML elements are removed

2.8k views Asked by At

This may not be the most clear way of asking what I'm asking but, I have a plugin that manages multiple grouped elements. It is my understanding that a plugin should be capable of destroying itself when the need/want arises. So my question is, is there any kind of hook that either jQuery or JavaScript will fire when a DOM element is removed from the page to assist in JavaScript's garbage collection and avoid memory leaks from event handlers and such? If I am unclear in what I am asking I apologize but I honestly don't know the best way to ask this question

1

There are 1 answers

1
rabelloo On BEST ANSWER

Yes, there is. Although you will need either jQuery UI or to write your own special event. The problem is it only works if the element is removed using jQuery. Aside from that, you would need to use DOM events or the recommended solution - DOM Mutation Observers.

These questions should help you further:

  1. jQuery - Trigger event when an element is removed from the DOM
  2. How to detect element being added/removed from dom element?

By the way, that is the keyword you missed - "event". That's what these "hooks" are called in jQuery/DOM.