JQuery trying to remove hidden div after x seconds?

Hi, I am trying to get a β€œhide” div and then β€œdelete” as soon as the hide animation is finished. It seems that I can either work, but not both. I tried to use setTimeout, but this only causes the div to become hidden, but not actually deleted.

Here is the code:

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

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

Any help appreciated!

+4
source share
4 answers

I think this is a problem. When your setTimeout() function starts, the this context is different from the function than what it was when you declared it.

Try the following:

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

Have you tried something like:

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

which will run the install code when the hide code is completed.

more about the callback: http://api.jquery.com/hide/

- fixed for this

+2
source

Hi everyone, thanks for the wonderful (and quick!) Answers! 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 new to this, and keep forgetting the callback (puts a hand to her forehead!)

@redsqure: Thanks for the feedback on performance! Still studying ...

@zombat: Yes, a good catch - I went around above by removing the call to the participants in the callback, as I was deleting the parent at this point .;)

@Tim: .delay (1000) looked promising, I couldn't get it to work (?) (Yes, I use 1.4);)

Thank you ppl! :)

+2
source

.hide accepts a full callback that you can use. Also .closest is more effective than the parents 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); 
0
source

Source: https://habr.com/ru/post/1299263/


All Articles