How to restart animation in CSS3 and JavaScript?

Sometimes, we want to restart animation in CSS3 and JavaScript.

In this article, we’ll look at how to restart animation in CSS3 and JavaScript.

How to restart animation in CSS3 and JavaScript?

To restart animation in CSS3 and JavaScript, we can get the offsetHeight property to trigger reflow.

For instance, we write

function resetAnimation() {
  const el = document.getElementById("animated");
  el.style.animation = "none";
  el.offsetHeight;
  el.style.animation = null;
}

const button = document.querySelector("button");
button.onclick = resetAnimation;

to create the resetAnimation function.

We get the element we want to animate with getElementById.

Then we get the offsetHeight to trigger reflow.

We clear el.style.animation by setting it to null.

Then we add our animation styles with

#animated {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: black;
  animation: bounce 3s ease-in-out infinite;
}

@keyframes bounce {
  0% {
    left: 0;
  }
  50% {
    left: calc(100% - 50px);
  }
  100% {
    left: 0;
  }
}

to set the animation styles of the element with ID animated.

And we add the elements with

<div id="animated"></div>
<button>Reset</button>

Conclusion

To restart animation in CSS3 and JavaScript, we can get the offsetHeight property to trigger reflow.