I have a css keyframe animation which loops.
animation-iteration-count: infinite
Now when I click a button I want the animation to finish the current loop and then stop.
this question seems related, but animationiteration webkitAnimationIteration callbacks don't seem to be called at the end of the keyframe animation, but more often.
EDIT: This turned out to almost be the correct solution, only that it can't handle multiple animations. For more info see my answer below.
This example shows my animation, and on hover I want to try to finish the current loop and then stop. This includes the answer proposed by @Alex Gru, It doesn't work if one wait for the animation to loop multiple times and then hover you can see the animation jumps. If it has not looped a full iteration and I set animation-iteration-count: 1 it works as intended.
CodePudding user response:
Here's a minimal solution for your use case:
First, add another class .stop when you want to finish the animation.
$(".target").addClass("stop");
Define the following css styling, which finishes the current cycle and stops the animation afterwards.
.target.stop {
-webkit-animation-iteration-count: 1;
animation: none;
}
Also see: Finish infinite iterations cycle and stop the animation with CSS
CodePudding user response:
So I found out why it didn't work. There is some additional information in how I've managed to get it to work after all, that I'll explain here.
It was my fault because there is another animation attached sub element:
<div id="a1"> <-- Main animation that should finish the loop
<div id="a2"></div> <-- sub animation that should not be finished
</div>
That was the reason why the animation call backs where triggered more often than expected. But: I found out that I can filter by animation name!
$("#a1").on('animationiteration webkitAnimationIteration', function(e) {
/* this triggers not only when animation of #a1 iterated but also if animation of #a2 iterated */
let animation_name = e.originalEvent.animationName;
if(animation_name == "animation1name"){
//This will only trigger if the correct animation iterated
}
});
I hope this solution can help someone who tries to handle multiple looping animations applied to one element (or sub element)
Thanks to everyone else who helped! ( I adjusted the question title in order to highlight what the problem actually was )
