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);
});
In your timeout function,
thisisn’t what you think it is – it’s actually the globalwindowobject.In any event (no pun intended) you should use a “completion callback”:
Never, ever, mix
setTimeoutand the animation queue. It’s fine to interleave the two, i.e having a completion 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 complete at the same time.EDIT fixed code – no need for
selfin a completion callback, I was still thinking aboutsetTimeoutandthiswhen I wrote that!