PHPnews.io

JavaScript: Restart all CSS Animations of an Element

Written by Bram.us / Original link on Jul. 20, 2022

css-animation.png

Recently built a demo that demonstrated a specific animation. Only problem: if you missed it, you had no way of restarting it. Instead of forcing the visitor to reload the page, this little JavaScript-snippet – attached to a button click – did the trick:

const restartAnimations = ($el) => {
	$el.getAnimations().forEach((anim) => {
		anim.cancel();
		anim.play();
	});
};

Pass in an Element, and it will will loops all attached animations bound to it. For each animation it restarts them by triggering a cancel + play.

~

Demo

See the Pen
JavaScript Restart Animations
by Bramus (@bramus)
on CodePen.

~

🔥 Like what you see? Want to stay in the loop? Here's how:

bram tutorialzine bram calevans tutorialzine bram

« Completing the 3 peaks challenge in 30 hours - The Road to PHP 8.2 »