Reputation: 33
I'm trying to trigger an animation as a callback to another animation. The things is I only want the second animation to fire if the first completes, and from what I've read that is how the .stop() function is supposed to work. In the code I've compiled however, the second animation fires even if the first does not complete.
Here's the code:
$(document).ready(function(){
var angle = 0;
function arrowRotate() {
angle +=180;
$('#arrow img').stop().rotate({
animateTo: angle,
}, 100);
};
function ToggleOpen(heightValue) {
$('#information').stop().animate({
height : heightValue,
}, 1500, 'easeOutExpo', function(){
arrowRotate();
})
};
$('#information_container').hover(function(){
ToggleOpen(500);
}, function(){
ToggleOpen(0);
});
$('#arrow img').click(function(){
ToggleOpen(0);
});
});
I'm using this third-party plugin: http://code.google.com/p/jqueryrotate/
Here's the live implementation: http://hopeandpurpose.org
So basically what I'm trying to accomplish is raising the height of a div on hover, and once that completes an image rotates. The problem is that the image still rotates even if the height animation does not complete and the div animates back to 0.
As I'm looking at the code now it seems that my problem is probably that as it hovers off, it triggers the arrowRotate() function. Would an if function wrapping the arrowRotate() function be my best solution?
Upvotes: 3
Views: 875
Reputation: 337590
Use stop(true)
to stop the animation, and also clear any queued animations waiting to run on the element.
Here's an example. If you mouse off before the height shrinks, you'll see that that animation is not run because it's cleared by stop(true)
in the mouseleave handler.
$("div").hover(function() {
$(this).stop(true).animate({ width: 300 }, function() {
$(this).animate({ height: 50 });
});
}, function() {
$(this).stop(true).animate({ width: 50, height: 100 });
}
);
#test {
width: 50px;
height: 100px;
background-color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">Test</div>
Upvotes: 3