Toggling Animations On and Off

Avatar of Chris Coyier
Chris Coyier on

A nicely detailed tutorial by Kirupa that gets into how you might provide a UI with persisted options that control whether animations run or not.

The trick is custom properties that control the movement:

body {
  --toggle: 0;
  --playState: "paused";
}

Which are used within animations and transitions:

.animation {
  animation: bobble 2s infinite;
  animation-play-state: var(--playState);
}

.transition {
  transition: transform calc(var(--toggle) * .15s) ease-in-out;
}

And toggle-able by JavaScript:

// stop animation
document.body.style.setProperty("--toggle", "0");
document.body.style.setProperty("--playState", "paused");

// play animation
document.body.style.setProperty("--toggle", "1");
document.body.style.setProperty("--playState", "running");

Then get into using the media query to test for reduced motion off the bat, and storing the preferred value in localStorage.

Direct Link →