18

Is there an official way to hook in to jQuery.remove() so that a function can be called before/after?

I have a system whereby certain handlers are attached to elements, and sometimes these elements are removed (eg. a UI widget whose primary element is removed by some other action on the page). If handlers could be notified that their primary element was removed, I can run cleanup routines a little easier.

Reporter
  • 3,897
  • 5
  • 33
  • 47
chroder
  • 4,393
  • 2
  • 27
  • 42
  • I just looked into the relevant code, https://github.com/jquery/jquery/blob/master/src/manipulation.js#L168 , and it is really just a thin wrapper around parent.removeChild. So go with @Drew's answer. – Boldewyn Apr 02 '12 at 09:40
  • Did you find any work around, besides wrapping the original remove event? – Mahn Nov 14 '14 at 19:56

3 Answers3

24

you can use jQuery.when():

$.when($('div').remove()).then( console.log('div removed') );
mcnesium
  • 1,423
  • 2
  • 16
  • 21
  • 5
    This gets the job done if you are looking for a way to remove the element *immediately* and have a callback fire after the removing is done. But removing the event in jQuery is a synchronous event, so for this purpose the answer here is redundant: you can achieve the exact same thing doing: `$('div').remove(); console.log('div removed');` – Mahn Nov 14 '14 at 19:53
  • 2
    As for *being notified later on* when an element is removed, which is what OP was asking, this will not do the trick (notice how `$('div').remove()` is called when passed as an argument of `when`; this effectively means the element is removed immediately) – Mahn Nov 14 '14 at 19:54
  • For those of you maddened jQuery's quirks, still finding this doesn't work: try a setTimeout() in addition to this. – Vael Victus Nov 16 '17 at 20:36
5

Use a custom event, attach handlers to the custom event that fire before/after the remove. For example,

$( document ).bind( 'remove', function( event, dom ){

    $( document ).trigger( 'beforeRemove', [ dom ] );
    $( dom ).remove();
    $( document ).trigger( 'afterRemove', [ dom ] );
});

$( document ).trigger( 'remove', 'p' ); //Remove all p's
Drew
  • 4,683
  • 4
  • 35
  • 50
3

Here's a nifty hack - you might wanna give it a try.

$('div').hide(1, function(){
    // callback
    $(this).remove();
});
Kenneth P.
  • 1,797
  • 3
  • 21
  • 31