jQuery remove() callback?
Asked Answered
H

3

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.

Housebreak answered 29/9, 2011 at 8:56 Comment(2)
I just looked into the relevant code, 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.Teresita
Did you find any work around, besides wrapping the original remove event?Nealon
C
24

you can use jQuery.when():

$.when($('div').remove()).then( console.log('div removed') );
Corbet answered 21/8, 2013 at 10:50 Comment(3)
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');Nealon
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)Nealon
For those of you maddened jQuery's quirks, still finding this doesn't work: try a setTimeout() in addition to this.Mohican
U
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
Ulphi answered 7/10, 2011 at 19:11 Comment(0)
Z
3

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

$('div').hide(1, function(){
    // callback
    $(this).remove();
});
Zoolatry answered 17/5, 2015 at 12:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.