Cassidy Williams

Software Engineer in Chicago

Cassidy's face

Pausing a CSS animation with getAnimations()


It’s Blogvent, day 9, where I blog daily in December!

CSS animations are cool, but sometimes you want them to just cool it.

You can pause them by using the getAnimations() method!

When you call getAnimations() on an element, you get an array of all of the Animation objects on said element, which includes CSS animations. There’s various things you can do with the returned Animation object, like getting the currentTime of the animation’s timeline, or the playback state of the animation (playState), or in our case, actually pausing the animation with pause().

We could loop through every Animation object in that array and pause it, like so:

const someAnimatedThing = document.querySelector(".thing");
const animations = someAnimatedThing.getAnimations();

animations.forEach((animation) => {
	animation.pause();
});

Or, if you just want one animation to pause, you can filter from the returned results.

Here’s a real demo where there’s only one animation happening, so we pause it based on the current playState.

See the Pen getAnimations() demo by Cassidy (@cassidoo) on CodePen.

Hope this was helpful!


View posts by tag

#advice #events #personal #musings #learning #work #recommendation #technical #project #meta