How to Control CSS Animations with JavaScript

By  on  

When it comes to animations on the web, developers need to measure the animation's requirements with the right technology -- CSS or JavaScript. Many animations are manageable with CSS but JavaScript will always provide more control. With document.getAnimations, however, you can use JavaScript to manage CSS animations!

The document.getAnimations method returns an array of CSSAnimation objects. CSSAnimation provides a host of information about the animation: playState, timeline, effect, and events like onfinish. You can then modify those objects to adjust animations:

// Make all CSS animations on the page twice as fast
document.getAnimations().forEach((animation) => {
  animation.playbackRate *= 2;
});

// Stop all CSS animations on the page
document.getAnimations().forEach((animation) => {
  animation.cancel();
});

How could adjusting CSS animations on the fly be useful to developers? Maybe use the Battery API to stop all animations when the device battery is low. Possibly to stop animations when the user has scrolled past the animation itself.

I love the way you can use JavaScript to modify CSS animations. Developers used to need to choose between CSS and JavaScript -- now we have the tools to make them work together!

Recent Features

  • By
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

Incredible Demos

  • By
    Submit Button Enabling

    "Enabling" you ask? Yes. We all know how to disable the submit upon form submission and the reasons for doing so, but what about re-enabling the submit button after an allotted amount of time. After all, what if the user presses the "stop"...

  • By
    Implementing Basic and Fancy Show/Hide in MooTools 1.2

    One of the great parts of MooTools is that the library itself allows for maximum flexibility within its provided classes. You can see evidence of this in the "Class" class' implement method. Using the implement method, you can add your own methods to...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!