Categories
JavaScript Answers

How to add CSS animation on click with JavaScript?

Spread the love

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.

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 *