0

I know we can stop a finite css animation via animation-fill-mode: forwards;. However, how to achieve the same effects for infinite animations? For example, for the following snippets, when pointerup is fired, how to stop the animation at 360deg state?

document.addEventListener("pointerup", () => {
  const div = document.getElementsByTagName("div")[0];
  // 
});
div {
  width: 100px;
  height: 100px;
  background: blue;
  position: relative;
  animation: ani 5s infinite;
}

@keyframes ani {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
<div></div>

Appendix:

  1. I know we can use timer in JS, and check whether pointerup is raised in each timer interval, however a solution with pure css or least js involved is preferred.
  2. We should ensure the solution works well in modern browsers, such as Google Chrome and Microsoft Edge.
Haibara Ai
  • 10,703
  • 2
  • 31
  • 47

2 Answers2

0

try this link

Stop infinite CSS3 animation and smoothly revert to initial state

You will get idea how to do so. Works fine for me.

Community
  • 1
  • 1
Rahul
  • 45
  • 2
  • 12
  • Thank you Rahul! Listening to `animationiteration` event perfectly solved my issue! Could you please elaborate your answer then I can mark it as accepted? – Haibara Ai Apr 26 '17 at 08:40
0

Try this:

div = document.getElementsByTagName("div")[0];
div.addEventListener("pointerup", (ev) => {
  ev.target.className = "stopme";
});
div {
  width: 100px;
  height: 100px;
  background: blue;
  position: relative;
  animation: ani 5s infinite;
}

div.stopme{
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
}

@keyframes ani {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
<div></div>
Vanojx1
  • 5,574
  • 2
  • 23
  • 37
  • Thanks for the answer, however this doesn't work when current iteration is > 1 (which will cause animation stops directly), ans also, it doesn't work in Microsoft Edge, though seems like a bug in Edge. – Haibara Ai Apr 26 '17 at 08:41