Go slowly   About  Contact  Archives

Reset Css Animation

There is no easy way to reset CSS animation when it starts playing, we have at least 2 “hacky” ways though.

This is the tip from Mozilla, use a nested requestAnimationFrame() to trigger re-render animation

function play() {
  document.querySelector(".box").className = "box";
  window.requestAnimationFrame(function(time) {
    window.requestAnimationFrame(function(time) {
      document.querySelector(".box").className = "box changing";
    });
  });
}
var el = document.querySelector(".box")
el.className = "box";
el.focus() // Or el.offsetLeft, el.offsetRight, etc
el.className = "box changing";

Have fun with CSS animation!

Written on August 4, 2020.