3

I have a couple situations where I need to animate an element, say either moving it to the left, or fading it in, but only after an initial animation is 100% complete.

So like, say I have a search drawer that slides out from the top of the page when you click a search icon. Thats easy right:

$('.search-toggle').on('click', function(){ $('.search-drawer').slideToggle(); // or fadeIn(), show() ect.. }); 

But what if like, I click on a search toggle at the BOTTOM of a page, and I need my page to scroll up to the top BEFORE displaying the search drawer? I tried something like this:

$('.search-toggle').on('click', function(){ $('html, body').animate({ scrollTop: 0 }, "slow").find('.search-drawer').slideToggle(); // or fadeIn(), show() ect.. }); 

but the two animations run at the same time. I've tried using delay but that doesn't seem to work and would likely cause a noticeable delay when the top link is click as opposed to the bottom.

That said, I'm also trying to run an animation where when you click on an element, I want it to move to the left by like 330px and then, AFTER it's reached that position, another element would slide in Or I would have the second element slide in first and THEN the first element would do something. The point is, how do I get the animated to finished before beginning another one.

So for my second example, I see that the animate callback doesnt really work. I have this for another animation:

 $first.animate( { left : "-=660" }, 300, function(){ $second.animate({ left: '-='+startPosition }); } } 

So in this example, in theory first $first would move left 660 pixels and THEN $second would move left X amount right? It doesnt, they look like the move at the same time. Or rather, $second starts animating before $first.

2
  • use callback function of animate method, check the DOC. And fix all the typos in your post... Commented Aug 8, 2013 at 18:10
  • Fixed! I was JUST doing that when you posted! Commented Aug 8, 2013 at 18:19

1 Answer 1

5

You need to change your function so it will wait for the first animation to complete:

$('.search-toggle').on('click', function(){ $("body").animate({ scrollTop: 0 }, "slow", function(){ $('.search-drawer').slideToggle(); // or fadeIn(), show() ect.. }); }); 
Sign up to request clarification or add additional context in comments.

4 Comments

need to fight to fix OP typos... ;)
Thanks, That seems to cause the slideToggle() to fire twice though. My page will scroll up and the drawer will open but it closes immediately.
That is because you were animating both html and body. I have updated my question.
So while the callback worked for the first example, it doesnt for the second example. I edited my question to include some sample code. And thanks, you two!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.