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
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

Incredible Demos

  • By
    CSS Columns

    One major gripe that we've always had about CSS is that creating layouts seems to be more difficult than it should be. We have, of course, adapted and mastered the techniques for creating layouts, but there's no shaking the feeling that there should be a...

  • By
    The Simple Intro to SVG Animation

    This article serves as a first step toward mastering SVG element animation. Included within are links to key resources for diving deeper, so bookmark this page and refer back to it throughout your journey toward SVG mastery. An SVG element is a special type of DOM element...

Discussion

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