The original has interactive demos you can play with: https://websgeek.com/restart-css-animation
The bug everyone writes first
You have a CSS animation tied to a class. Something happens — a click, a new item — and you want the animation to play again, so inside one handler you remove the class and add it right back. The element keeps animating as if you touched nothing. No new animation is created, no animationstart event fires.
The reason is when the browser looks. A CSS animation starts only when the computed value of animation-name changes between two style updates. Class changes are just notes attached to the element until the browser recalculates style, which normally happens after your script task finishes. Remove and re-add inside one task and you get a single style update whose before and after are identical: the comparison is wg-slide against wg-slide. The rule has nothing to do with classes — it is about whether two different computed values were ever seen. That is why removing the class in one action and adding it back in another does work: the name really spent a moment as none.
Every fix below makes the browser compute style twice — or drives the animation from script instead.
Fix one: force a style calculation
Read a geometry property between your two writes:
box.classList.remove('run');
void box.offsetWidth; // forces style recalc + layout, now
box.classList.add('run'); // the name truly changed: restart
offsetWidth cannot be answered from stale data, so the browser recalculates style — and runs layout — before returning the number. For one moment the element genuinely exists with animation-name: none.
This is a forced synchronous layout. Once per click it is harmless; in a loop that alternates reads and writes it becomes layout thrashing. The void just tells the next reader you want the side effect, not the number — getBoundingClientRect() works too. And toggling style.animation = 'none' then back fails for exactly the reason in the first section, unless you put the read in between.
Fix two: swap the animation name
A restart does not need the name to become none; it needs the name to become different. Define two @keyframes blocks with identical contents and different names, then alternate between them. Every press is a real change of computed value, so a fresh animation is created — synchronously, with zero layout cost.
The price is duplication: the two blocks must stay identical forever, which is why this fix pairs well with generated stylesheets. Mind the shorthand trap — a later animation: declaration resets animation-name, so set the name after the shorthand or use longhands only.
Fix three: drive it from script
Every CSS animation is also an Animation object. el.getAnimations() returns the live instances, and cancel() followed immediately by play() throws the old run away and starts the same animation from frame zero — no classes, no layout read, no duplicated keyframes. It works on a running, paused or finished animation alike.
for (const anim of box.getAnimations()) {
anim.cancel(); // idle: fill gone, animationcancel fires
anim.play(); // frame zero, same options, same keyframes
}
Two traps. cancel() clears the fill, so a forwards fill belonging to the cancelled run goes with it and the element snaps home. And a cancelled CSS animation is unreachable until animation-name changes, because the computed name never changed and the browser never creates a replacement. If an old engine objects to cancel() + play(), the sequence pause(), currentTime = 0, play() does the same job. Support has been everywhere since 2020 — Chrome 84, Firefox 75, Safari 13.1.
This is the one to reach for first in real code. A helper that also respects reduced motion:
const calm = matchMedia('(prefers-reduced-motion: reduce)');
function restartAnimations(el) {
if (calm.matches) return 0; // no decorative replays
const anims = el.getAnimations({ subtree: true });
anims.forEach(a => { a.cancel(); a.play(); });
return anims.length; // 0 when CSS disabled it
}
With { subtree: true }, one button restarts every animation inside a card. The reduced-motion check sits inside the helper on purpose: your CSS tones the animation down, and the helper refuses to replay what remains, so readers who ask for less motion get one consistent story.
Fix four: replace the element
A brand-new element has no animation history, so the very same CSS animation starts the moment it is inserted. Clone the node, replace the old one, and it replays — the one fix that needs no understanding of style updates at all.
The costs live elsewhere: cloneNode() copies attributes, not live state, so typed text reverts; listeners bound directly to the old node stop firing — delegate them; and focus falls back to <body> if the replaced subtree contained the focused element. Use this only where content is re-rendered from a template regardless — toasts, list rows.
Which one belongs in your code?
Use the API for anything you already control from script, which is most UI code. Use the forced reflow for a one-line fix in old code or old browsers. Use the name swap where stylesheets are generated anyway. Replace the node only when its content is re-rendered regardless and you already delegate events. And if you restart the same animation constantly, maybe a spring or a transition expresses a repeated action better.
Try it live: play with the interactive demos at websgeek.com/restart-css-animation
Written with AI assistance and checked against the original article by the WebsGeek team.
Top comments (0)