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.

rugbert
  • 11,603
  • 9
  • 39
  • 68

1 Answers1

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..
    });
});
putvande
  • 15,068
  • 3
  • 34
  • 50
  • 1
    need to fight to fix OP typos... ;) – A. Wolff Aug 08 '13 at 18:12
  • 1
    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. – rugbert Aug 08 '13 at 18:20
  • 2
    That is because you were animating both `html` and `body`. I have updated my question. – putvande Aug 08 '13 at 18:23
  • 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! – rugbert Aug 08 '13 at 19:07