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.

Trigger CSS Animations in JavaScript

To trigger CSS animations in JavaScript, we just add the class that is set to animate the keyframes in CSS.

For instance, if we have:

<div class='TimeCountdown_circle1'>
  circle
</div>
<div class='TimeCountdown_circle2'>
  circle
</div>

Then we add animation with:

@keyframes circle1 {
  from {
    background-color: red;
  }

  to {
    background-color: yellow;
  }
}

@keyframes circle2 {
  from {
    background-color: red;
  }

  to {
    background-color: yellow;
  }
}

.circle_ani1,
.circle_ani2 {
  animation-duration: 1s;
  animation-iteration-count: 1;
}

.circle_ani1 {
  animation-name: circle1;
}

.circle_ani2 {
  animation-name: circle2;
}

We add the @keyframes property with the animation we want to animate.

It’ll animate from the from styles to the to styles.

Then we set the animation-name to the keyframes we want to animate within the class selectors.

Next, we write:

const tempCircle1 = $('.TimeCountdown_circle1').removeClass('circle_ani1');
const tempCircle2 = $('.TimeCountdown_circle2').removeClass('circle_ani2');
window.setTimeout(() => {
  tempCircle1.addClass('circle_ani1');
  tempCircle2.addClass('circle_ani2');
}, 50);

to remove the circle_ani1 and circle_ani2 classes with jQuery’s removeClass after we select them.

Then we call addClass to add the classes to the elements.

Conclusion

To trigger CSS animations in JavaScript, we just add the class that is set to animate the keyframes in CSS.

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 *