How to add CSS animation on click with JavaScript?

Sometimes, we want to add CSS animation on click with JavaScript.

In this article, we’ll look at how to add CSS animation on click with JavaScript.

How to add CSS animation on click with JavaScript?

To add CSS animation on click with JavaScript, we add animation effects for a class.

For instance, we write

.classname {
  -webkit-animation-name: cssAnimation;
  -webkit-animation-duration: 3s;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-timing-function: ease;
  -webkit-animation-fill-mode: forwards;
}

@-webkit-keyframes cssAnimation {
  from {
    -webkit-transform: rotate(0deg) scale(1) skew(0deg) translate(100px);
  }
  to {
    -webkit-transform: rotate(0deg) scale(2) skew(0deg) translate(100px);
  }
}

to add animation to the classname class.

In it, we add the keyframes for the animation.

Then we write

const ani = () => {
  document.getElementById("img").className = "classname";
};

to define the ani function that selects the element to animate with getElementById.

And we set its className to 'classname' to apply the animation effects that’s applied for the class.

Conclusion

To add CSS animation on click with JavaScript, we add animation effects for a class.