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

Incredible Demos

  • By
    Editable Content Using MooTools 1.2, PHP, and MySQL

    Everybody and their aerobics instructor wants to be able to edit their own website these days. And why wouldn't they? I mean, they have a $500 budget, no HTML/CSS experience, and extraordinary expectations. Enough ranting though. Having a website that allows for...

  • By
    MooTools, mediaboxAdvanced, and Mexico

    The lightbox is probably one of my favorite parts of the Web 2.0 revolution. No more having to open new windows (which can bog down your computer quite a bit) to see a larger image, video, etc. Instead, the item loads right into the...

Discussion

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