Reputation: 85
I'm running the following jQuery animation but without a good sequence flow.
What's the best way to run the following animation (fadeTo, animate, fadeTo) in sequence from top to bottom listed below.
$(".needGray").fadeTo("slow",0.2);
$(".turnLeft").animate({scrollTop:0}, '500');
$(".needGray").fadeTo("slow",1.0);
Upvotes: 0
Views: 139
Reputation: 35953
Call the .stop() method between animations to prevent jQuery from building them up in a queue which may cause your animation to appear jumpy.
The default behavior of jQuery is to queue each animation task it is to run in a sequence and run each of them. But often times, this list gets a bit confused and each task starts trying to step on top of the previous.
By calling .stop()
you ensure that any running animation is stopped before running the next one. It effectively clears the queue after each animation so there never is a queue or a buildup of tasks.
You may also find it better to use animate
rather than fadeTo
as I believe that animate
is processed faster than `fadeTo', at least in this benchmark test it was for me. It's also a good idea to breakup any linear animations into smaller chunks whenever possible; you can design this using a loop to increment the animation over several smaller steps. For example, in your case, you could run a loop to step the opacity of needGray +0.2, 5 times and only on the first iteration process the additional animation for scrollTop.
Here's a simplified example..
var $i = 1;
$("#start").hover(function() {
setInterval(function() {
while ($i <= 5) {
$('.needGray').animate({'opacity':$i/4});
if ($i == 1) {
$('.turnLeft').stop().animate({'margin-left':150},500);
}
$i++
}
},250);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="needGray" style="width:50px;height:50px;background:#ccc;"></div>
<div class="turnLeft" style="width:50px;height:25px;background:#eee;"></div>
<br><br>
<div id="start">Begin Sequence</div>
Upvotes: 1
Reputation: 21482
Call each subsequent animation in the "complete" callback of the previous one:
$(".needGray").fadeTo("slow", 0.2, function() {
$(".turnLeft").animate({scrollTop:0}, '500', function() {
$(".needGray").fadeTo("slow",1.0);
});
});
Animations run asynchronously. Although when they apply to the same element, they are placed in a queue. That means with your original code the second fadeTo
will not run until the first is complete, but the animate
starts right away. These functions can all take a 'complete' callback though, which is not called until the animation is complete.
Upvotes: 1
Reputation: 3872
Use "complete" function:
$(".needGray").fadeTo("slow", 0.2, function (){
$(".turnLeft").animate({scrollTop:0}, '500', "easein", function (){
$(".needGray").fadeTo("slow",1.0);
});
});
Upvotes: 1