Reputation: 16436
I have the following HTML:
<div class="rotate"></div>
And the following CSS:
@-webkit-keyframes rotate {
to {
-webkit-transform: rotate(360deg);
}
}
.rotate {
width: 100px;
height: 100px;
background: red;
-webkit-animation-name: rotate;
-webkit-animation-duration: 5s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
}
I want to know if there is a way (using JavaScript) to stop the animation but let it finish its current iteration (preferably by changing one or a few CSS properties). I have tried setting -webkit-animation-name
to have a blank value but that causes the element to jump back to its original position in a jarring fashion. I have also tried setting -webkit-animation-iteration-count
to 1
but that does the same thing.
Upvotes: 32
Views: 11863
Reputation: 11
In case anyone else is coming to this later, here is my solution in React using
const [animationPlaying, setAnimationPlaying] = useState<boolean>(false);
...
<div
onAnimationIteration={() => {
// do 1 more full animation before ending
if (condition) {
setAnimationPlaying(false);
}
}}
style={{
animation: `${customAnimation} 1s infinite`,
animationPlayState: animationPlaying ? 'running' : 'paused',
}}
/>
Upvotes: 0
Reputation: 179402
Stop the animation upon receiving an animationiteration
event. Something like this (using jQuery):
CSS
@-webkit-keyframes rotate {
to {
-webkit-transform: rotate(360deg);
}
}
.rotate {
width: 100px;
height: 100px;
background: red;
}
.rotate.anim {
-webkit-animation-name: rotate;
-webkit-animation-duration: 5s;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: linear;
}
HTML
<div class="rotate anim">TEST</div>
<input id="stop" type="submit" value="stop it" />
JS (JQuery)
$("#stop").click(function() {
$(".rotate").one('animationiteration webkitAnimationIteration', function() {
this.classList.remove("anim");
});
});
Fiddle: http://jsfiddle.net/jmp2fakn/
Note that I'm using .one
here (not .on
) so that the handler only runs once. That way, the animation can later be restarted.
Upvotes: 36
Reputation: 11
Do you mean you want the animation to stop where it is when it ends without jumping back to its original position?
Then you want:
Animate something moving from one place to another and have it stay there: animation-fill-mode:forwards;
check this link:
http://www.w3schools.com/cssref/css3_pr_animation-fill-mode.asp
Upvotes: 1