Trigger CSS Animations in JavaScript

Sid picture Sid · Jun 30, 2017 · Viewed 46.3k times · Source

I don't know how to use JQuery, so I need a method which could trigger an animation using JavaScript only.

I need to call/trigger CSS Animation when the user scrolls the page.

Answer

Blackbam picture Blackbam · Jun 30, 2017

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