Chapter 8. The Web Animations API


There are a few different ways to animate elements in modern web browsers. Chapter 1 had an example of using the requestAnimationFrame API to manually animate an element (see “Animating an Element with requestAnimationFrame”). This gives you a lot of control, but at a cost. It requires keeping track of timestamps to calculate frame rates, and you must calculate each incremental change of the animation in JavaScript.

Keyframe-Based Animation

CSS3 introduced keyframe animations. You specify the beginning style, ending style, and a duration within CSS rules. The browser automatically interpolates, or fills in, the intermediate frames of the animation. Animations are defined with the @keyframes rule and used via the animation property. Example 8-1 defines a fade-in animation.

Example 8-1. Using a CSS keyframe animation
@keyframes fade {
  from {
    opacity: 0;

  to {
    opacity: 1;

.some-element {
  animation: fade 250ms;

A fade-in animation starts with an opacity of 0 and ends with an opacity of 1. When the animation runs, the browser calculates the intermediate style frames over the course of 250 milliseconds. The animation starts as soon as the element enters the DOM or the some-element class is applied.

Keyframe Animation with JavaScript

The Web Animations API lets you use keyframe animations in your JavaScript code. The Element interface has an animate method where you can define the keyframes and other options of the animation. ...

Get Web API Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.