dcp3450
dcp3450

Reputation: 11187

Why is the callback in jQuery slideUp() not waiting for the animation to finish?

What I want is fairly simple:

I have a container with a background. Inside the container are triggers and hidden boxes like so:

<div id="container">

<span id="box-1">Open 1</span> <span id="box-2">Open 2</span> <span id="box-3">Open 3</span> <span id="box-4">Open 4</span> <span id="box-5">Open 5</span> 

<div class="box box-1">Hi! I'm Box 1</div>
<div class="box box-2">Hi! I'm Box 2</div>
<div class="box box-3">Hi! I'm Box 3</div>
<div class="box box-4">Hi! I'm Box 4</div>
<div class="box box-5">Hi! I'm Box 5</div>

</div>

Once a trigger is clicked a target box slides down. If a box is open already it slides up and the new target box slides down. I have this working on a different part of the site but it's a bit more complex to share in jsfiddle. The simple version I can't get to work correctly is here:

jsFiddle: slideUp and slideDown issue

It seems that the slideDown function is starting before the slideUp completes. I've moved the slideDown outside the slideUp callback and I get the same reaction. I've worked with duration and delay but it still has the same issues.

----- EDIT -----

I should note that my goals is for the container to collapse completely before expanding again.

Upvotes: 1

Views: 3687

Answers (3)

Gak2
Gak2

Reputation: 2701

This question is 6 months old, but I found out the answer to the problem. It's that using $('.box').not(boxItem).slideUp(function() will call the slideUp function 4 times, since there are 4 other divs with the class "box". We only want it to be called once since there is only one div to slide up. You should keep track of which box is currently open, and use that as the selector instead of '.box'.

Upvotes: 3

wirey00
wirey00

Reputation: 33661

It's because you need to hide() before you slidedown again

$('.box').not(boxItem).slideUp(function(){
    $('.box'+boxItem).hide().slideDown();
});

http://jsfiddle.net/dYMx8/

Upvotes: 8

Johan
Johan

Reputation: 35194

Try stopping the animation:

$('.box').not(boxItem).stop(true, true).slideUp(function(){
    $('.box'+boxItem).slideDown();
});

Passing true, true will clear the animation queue and make the animation "jump to the end"

Fiddle

http://api.jquery.com/stop/

Upvotes: 0

Related Questions