Play, Pause & Restart CSS Animations

css
Published on March 12, 2021

Playing & pausing a CSS animation can be done by using the animation-play-state property.

animation-play-state: paused pauses the animation, while animation-play-state: running starts playing the animation again.

In Javascript animation-play-state CSS property of the element can be referenced through animationPlayState.

Completely restarting the animation can be done by first removing the animation and then applying it again.

Example

HTML, CSS & Javascript :

<!-- animated element -->
<div id="box"></div>

<!-- pause / play / restart buttons -->
<button id="pause">Pause</button>
<button id="play">Play</button>
<button id="restart">Restart</button>
#box {
	animation: alternate 2s infinite shrink ease-in-out;
}

@keyframes shrink {
	from { transform: scale(1); }
	to { transform: scale(0); }
}
// pause animation
document.querySelector("#pause").addEventListener('click', function() {
	document.querySelector("#box").style.animationPlayState = 'paused';
});

// play animation
document.querySelector("#play").addEventListener('click', function() {
	document.querySelector("#box").style.animationPlayState = 'running';
});

// restart animation
document.querySelector("#restart").addEventListener('click', function() {
	// remove animation 
	document.querySelector("#box").style.animation = 'none';

	// trigger reflow
	document.querySelector("#box").offsetWidth;

	// add animation again
	document.querySelector("#box").style.animation = 'alternate 2s infinite shrink ease-in-out';
});

Pausing Animation

The animation of the element can be paused by setting animationPlayState style property to paused using Javascript.

document.querySelector("#box").style.animationPlayState = 'paused';

Playing Animation

The animation can be played back from the paused state by setting animationPlayState property to running.

document.querySelector("#box").style.animationPlayState = 'running';

Restarting Animation

To restart the animation, the animation style property needs to be removed, and then applied back.

Note that between the animation removal & re-apply, a DOM reflow needs to be explicitly triggered so that it forces the browser to re-calculate style & layout. If the reflow is not triggered, then both animation removal & re-apply will be executed in a single go, and there will be no difference in the animation state.

PS: DOM reflows are bad for page performance.

// remove animation 
document.querySelector("#box").style.animation = 'none';

// trigger reflow
document.querySelector("#box").offsetWidth;

// add animation again
document.querySelector("#box").style.animation = 'alternate 2s infinite shrink ease-in-out';

There are several ways to force a reflow.

In this Tutorial