I am attempting to remove an object from a page with jQuery. I also want to animate the removal. The goal is to make the element fadeOut(), wait a second, then remove(). But it seems to refuse to wait to remove the element, even when I use it in a setTimeout() function. How can I make an element fadeOut(), and then remove() it?
$("button").click(function() {
$(this).fadeOut();
setTimeout(function() { $(this).remove();}, 1000);
});
I am attempting to remove an object from a page with jQuery. I also want to animate the removal. The goal is to make the element fadeOut(), wait a second, then remove(). But it seems to refuse to wait to remove the element, even when I use it in a setTimeout() function. How can I make an element fadeOut(), and then remove() it?
$("button").click(function() {
$(this).fadeOut();
setTimeout(function() { $(this).remove();}, 1000);
});
Share
Improve this question
edited May 22, 2012 at 15:46
dda
6,2132 gold badges27 silver badges35 bronze badges
asked May 22, 2012 at 14:34
jcrowleyjcrowley
712 silver badges10 bronze badges
0
5 Answers
Reset to default 8Read manual carefully: http://api.jquery./fadeOut/
The fadeOut() method has a callback that is invoked after the fadeOut pletes. To use it:
$("button").click(function() {
$(this).fadeOut(function() { $(this).remove();});
});
There should be no reason to wait one second after the fadeOut pletes, before removing the element, because the element will be invisible when it is removed.
In your timeout function, this
isn't what you think it is - it's actually the global window
object.
In any event (no pun intended) you should use a "pletion callback":
$("button").click(function() {
$(this).fadeOut('slow', function() {
$(this).remove();
});
});
Never, ever, mix setTimeout
and the animation queue. It's fine to interleave the two, i.e having a pletion callback start a timer, or having a timer starting an animation, but it's never OK to assume that you can start both a 1000ms animation and a 1000ms timer and have them plete at the same time.
EDIT fixed code - no need for self
in a pletion callback, I was still thinking about setTimeout
and this
when I wrote that!
$('button').click(function(){
$(this).fadeOut(function(){$(this).remove()});
});
DEMO
Why not just use the callback of fadeout?
$("button").click(function() {
$(this).fadeOut(function(){$(this).remove();});
});
try this one, maybe it helps:
$("button").click(function() {
(function(that) {
that.fadeOut();
setTimeout(function() {
that.remove();
}, 1000);
})($(this));
});