views:

370

answers:

4

Hey there, I am trying to have a div "hide", then "remove" once the hide animation is finished. It seems I can get either to work, but not both. I have tried using the setTimeout, but this only results in the div getting hidden, but not actually removed.

Here is the code:

$(this).parents("div:eq(0)").hide("fast");
setTimeout(function () { $(this).parents("div:eq(0)").remove();}, 1000);

If I do the remove without the setTimeout, it removes the div, but does not display the hide animation.

Any help appreciated!

+2  A: 

have you tried something like:

$(this).parents("div:eq(0)").hide("fast", function(){
    var div = this;
    setTimeout(function () { $(div).remove(); }, 1000);
});

that will run the settimeout code when the hide code has finished.

more info here on the callback: http://api.jquery.com/hide/

--fixed for the scope of this

John Boker
A: 

.hide takes a complete callback that you could use. Also .closest is more efficent than the parents first that you are currently using.

var $div = $(this).closest('div');

$div.hide("fast", function(){
    $div.remove();
});

To use setTimeout you would do

var $div = $(this).closest('div');

$div.hide("fast");

window.setTimeout(function () { 
      $div.remove();
}, 1000);
redsquare
+6  A: 

I believe it's a scoping issue. When your setTimeout() function runs, the context of this is different inside the function than what it was when you declared it.

Try this:

var self = $(this).parents("div:eq(0)");
self.hide("fast");
setTimeout(function () { self.remove();}, 1000);
zombat
why do the .parents leg work twice? Remember this traverses all parents
redsquare
@redsquare - good call. I was only paying attention to the scoping, not the actual selectors when I wrote it. I updated it to be a bit more efficient.
zombat
then use closest also ;)
redsquare
A: 

Hey all, thanks for the awesome (and fast!) responses! Appreciate it.

I ended up using a combination of several of them that seems to work well.

$(this).closest("div").hide("fast", function() {
    $(this).remove();
});

@John: Thanks! I'm fairly new to this, and keep forgetting about the callback (smacks hand to forehead!)

@redsqure: Thanks for the efficiency tip! Still learning...

@zombat: Yes, good catch - I got around it in the above with removing the call to the partents in the call back, as I was removing the parents's parent at that point. ;)

@Tim: The .delay(1000) looked promising, I couldn't get it to work(?) (yes, I'm using 1.4) ;)

Thanks ppl! :)

TwstdElf