100

I have this line of JavaScript and the behavior I am seeing is that the selectedLi instantly disappears without "sliding up". This is not the behavior that I expected.

What should I be doing so that the selectedLi slides up before it is removed?

selectedLi.slideUp("normal").remove();
Eric Schoonover
  • 47,184
  • 49
  • 157
  • 202

5 Answers5

207

Might be able to fix it by putting the call to remove in a callback arg to slideUp?

e.g

selectedLi.slideUp("normal", function() { $(this).remove(); } );
Owen
  • 82,995
  • 21
  • 120
  • 115
seanb
  • 6,969
  • 2
  • 33
  • 34
  • 4
    Note that "slow" and "fast" are the only speeds. Other speeds need to either be in milliseconds or they will default to 400. http://www.keyframesandcode.com/resources/javascript/deconstructed/jquery/#speeds – bendman Jan 24 '14 at 12:17
22

You need to be more explicit: rather than saying "this" (which I agree should work), you should do this:

$("#yourdiv").slideUp(1000, function() {
    $(this).remove();
});
PowerOfM
  • 303
  • 4
  • 8
Blake
  • 229
  • 2
  • 2
  • 2
    SORRY = i forgot to remove my id, should be: $('#yourdiv').slideUp(1000, function(){ $('#yourdiv').remove(); }); – Blake Jan 27 '11 at 13:49
  • 13
    Using $(this) instead of $("#yourdiv") is more optimized since jQuery does not need to look for a node. – MaximeBernard Jul 27 '13 at 16:52
  • Using `$("#yourdiv")` instead of `$(this)` is completely redundant and that's not why this code fixes OP's problem. This code fixes the problem because it uses the `complete` callback. – Gavin Aug 03 '15 at 16:08
9

The simplest way is calling the "remove()" function inside slideUp as a parameter like others have said, as this example:

$("#yourdiv").slideUp("normal", function() {
    $(this).remove();
});

It is a must to call it inside the anonymous function() to prevent remove() to be executed before the slideUp has ended. Another equal way is to use the jQuery function "promise()". Better for those who like self-explanatory code, like me ;)

$("#yourdiv").slideUp("normal").promise().done(function() {
    $(this).remove();
});
xaviqv
  • 111
  • 1
  • 1
4

Using promises you can also wait for multiple animations to get finished, e.g.:

selectedLi.slideUp({duration: 5000, queue: false})
.fadeOut({duration: 3000, queue: false})
.promise().done(function() {
    selectedLi.remove()
})
famousgarkin
  • 13,687
  • 5
  • 58
  • 74
-3
selectedLi.slideUp(200, this.remove);