Categories
JavaScript Answers

How to trigger CSS animations in JavaScript?

Spread the love

Sometimes, we want to trigger CSS animations in JavaScript.

In this article, we’ll look at how to trigger CSS animations in JavaScript.

How to trigger CSS animations in JavaScript?

To trigger CSS animations in JavaScript, we add keyframes for our animation.

For instance, we write

@keyframes spin1 {
  100% {
    transform: rotate(360deg);
  }
}
@keyframes spin2 {
  100% {
    transform: rotate(-360deg);
  }
}
@keyframes idle {
  100% {
  }
}

to add keyframes for the spin1, spin2, and idle animations.

Then we make our element animate by writing

document.getElementById("yourElement").style.animation =
  "spin2 4s linear infinite";

We select the element with getElementById.

Then we set its style.animation property to a string that has the animation name.

Conclusion

To trigger CSS animations in JavaScript, we add keyframes for our animation.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *