Trigger CSS Animations in JavaScript
This is how you can use vanilla JavaScript to change/trigger an animation associated with an HTML element.
First, you define your animations in CSS.
@keyframes spin1 { 100% { transform:rotate(360deg); } }
@keyframes spin2 { 100% { transform:rotate(-360deg); } }
@keyframes idle { 100% {} }
Then you use javascript to switch between animations.
document.getElementByID('yourElement').style.animation="spin2 4s linear infinite";
Note: 'yourElement' is the target HTML element that you wish to animate.
For example: <div id="yourElement"> ... </div>
The simplest method to trigger CSS animations is by adding or removing a class - how to do this with pure Javascript you can read here:
How do I add a class to a given element?
If you DO use jQuery (which should really be easy to learn in basic usage) you do it simply with addClass
/ removeClass
.
All you have to do then is set a transition to a given element like this:
.el {
width:10px;
transition: all 2s;
}
And then change its state if the element has a class:
.el.addedclass {
width:20px;
}
Note: This example was with transition. But for animations its the same: Just add the animation on the element which has a class on it.
There is a similar question here: Trigger a CSS keyframe animation via scroll