# Restart a CSS animation

Source: https://websgeek.com/restart-css-animation
Publisher: WebsGeek (https://websgeek.com), updated 2026-11-29

By the end you will know why re-adding a class never restarts a CSS animation, and which of the four real fixes — forced reflow, swapped animation name, Web Animations API, or a replaced element — belongs in your code.

## Why adding the class again does nothing

A CSS animation starts only when the computed value of `animation-name` changes between two style updates. Removing a class and adding it back inside one script task produces a single style update whose before and after are identical, so the browser never sees a change: no new animation is created, no `animationstart` event fires, and a running animation simply carries on as if you had touched nothing.

The panel below has one animated box and three buttons. The counter watches `animationstart`, which the browser fires only when a new animation instance is created. Two of the buttons work. The third is the one everyone writes first.

> Interactive demo: Remove the class, add it back (try it on the page).

Press **Remove class**, then **Add class**: the box replays, because the name really spent a moment as `none`. Now press **Both, one click** during a run — the box keeps going and the counter does not move. Then press **Remove class** once and try **Both, one click** again. This time it works, because before that click the computed name really was `none`. The rule has nothing to do with classes; it is about whether two different computed values were ever seen.

**One level deeper.** Class changes are only notes attached to the element until the browser recalculates style, which normally happens after your script task finishes. On every recalculation the animation machinery compares the new computed `animation-name` with the previous one and creates or cancels animations to match. Both of your edits landed before the recalculation, so the comparison is `wg-slide` against `wg-slide`. It is the same trap as the transition version we covered in [Transitions that skip the start](https://websgeek.com/css-transition-not-working-class-added), and every fix below is a way to make the browser compute style twice.

## Fix one: force a style calculation

The oldest fix makes the browser flush pending style changes synchronously: read a geometry property between your two writes. `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`.

> Interactive demo: Restart with a forced reflow (try it on the page).

The readout measures the read itself, in milliseconds, in your browser. On a clean tree the restart is close to free. Turn on the switch and 150 nodes get wider or narrower before each restart, so the forced layout has real work to do — watch the number climb. That is main-thread work you pay on every restart, whether or not anything is visible.

**Two style updates inside one task.**

```
box.classList.remove('run');  
void box.offsetWidth;    // forces style recalc + layout, now
box.classList.add('run'); // the name truly changed: restart
```

**One level deeper.** This is a forced synchronous layout. Once per click it is harmless; in a loop that alternates reads and writes it becomes layout thrashing, because every read after every write re-runs layout from scratch. 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 from section 1 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 — and no layout is ever read.

> Interactive demo: Same name vs swapped name (try it on the page).

In the left lane the button writes the name the box already has: nothing happens, exactly like section 1. In the right lane the button alternates `wg-slide` and `wg-slide-b`: a restart on every press, synchronously, with zero layout cost.

The price is duplication. Two keyframes 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. Every swap fires `animationstart` again, which for a replay button is usually exactly what you want.

**Two identical keyframes, one flip.**

```
/* Same movement, two names. */
@keyframes slide   { from { transform: none } to { transform: translateX(733%) } }
@keyframes slide-b { from { transform: none } to { transform: translateX(733%) } }

btn.addEventListener('click', () => {
  flip = !flip;
  box.style.animationName = flip ? 'slide-b' : 'slide';
});
```

## 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. It does not work on one you cancelled a moment ago, and the panel below shows why that trap matters.

> Interactive demo: The same animation, driven by script (try it on the page).

Watch `playState` move from `running` to `finished` at 1.60 s. Then press **cancel()** alone: `getAnimations()` comes back empty, and the box snaps home because a `forwards` fill belonged to the cancelled run and went with it. The panel is not dead, though — press **restart**, **pause** or **play** next and it attaches a fresh animation by flipping the inline `animation-name` to `none` and back across one forced reflow: fix one smuggled inside fix three. The readout counts the revives.

**One level deeper.** The object you get back is a `CSSAnimation`, a subclass of the same `Animation` that `element.animate()` returns, so it shares one state machine: `idle`, `running`, `paused`, `finished`. `cancel()` moves it to `idle`, fires `animationcancel`, clears its fill and removes it from `getAnimations()`; because the computed `animation-name` never changed, the browser never creates a replacement, so the cancelled run is unreachable until the name changes — the same law as section 1, arriving from a direction you did not expect. Pass `{ subtree: true }` to catch animations on every descendant of a card. Every current browser has shipped this since 2020 — Chrome 84, Firefox 75, Safari 13.1 — so only an old support matrix forces you back to the reflow.

**The restart that touches nothing else.**

```
for (const anim of box.getAnimations()) {
  anim.cancel(); // idle: fill gone, animationcancel fires
  anim.play();   // frame zero, same options, same keyframes
}
```

## 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. Its costs live somewhere else entirely.

> Interactive demo: Replace the node, replay the pop (try it on the page).

Click the inner button, type something, then replace. The pop replays — and the typed text reverts, because `cloneNode()` copies attributes, not live state. The direct counter freezes: that listener belonged to the old node. The delegated listener on the well keeps counting, which is the standard cure — delegate your events, or re-bind them after every swap. Focus is lost too: if the replaced subtree contained the focused element, focus falls back to `<body>`.

## Four fixes on one clock

Now press all four in one place. Each lane below runs the same keyframes with a different restart technique, and the bars and numbers are drawn from `getAnimations()` on every frame — the readout prints each lane's `currentTime`, so you can watch all four restart in the same tick and finish together.

> Interactive demo: Four restarts, one timeline (try it on the page).

What each lane costs you: the reflow lane pays a synchronous layout, measured in section 2. The swap lane pays duplicated keyframes. The API lane needs browsers from 2020 or later and nothing else. The replace lane silently discards listeners, form state and focus, as section 5 showed. The bars come from the animations themselves rather than a timer that guesses, and the update loop stops itself the moment nothing is running — a pattern we went into in [Timers that miss the frame](https://websgeek.com/requestanimationframe-vs-settimeout).

## A helper to copy, and when to use which

In real code I reach for the Web Animations API first: it restarts exactly what is on screen, finished or not, without touching classes or layout. Here is the whole helper — it reads as documentation the day someone else opens your file.

**A restart helper that 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
}
```

> Interactive demo: restartAnimations() in use (try it on the page).

One button restarts every animation inside the card, the slide and the badge's pop, because of `{ subtree: true }`. The reduced-motion check sits inside the helper on purpose: your CSS tones the animation down, and the helper refuses to replay what remains. Readers who ask for less motion get one consistent story instead of two.

This page practices what the helper preaches. Under `prefers-reduced-motion` the demo keyframes are redefined as opacity fades, so no box slides, pops or scales across your screen whether the name came from a class or an inline style — only the thin progress bars keep growing, because they are the live readout, not decoration. The helper sees what little remains and skips it, which is the report you saw in the note above.

**When to use which.** 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 — one click, one read, no harm. Use the name swap where stylesheets are generated anyway, so the duplicate keyframes cost nothing. Replace the node only when its content is re-rendered from a template regardless, such as toasts and list rows, and you already delegate events. And if you catch yourself restarting the same animation constantly, ask whether a spring or a transition expresses a repeated action better — we built [springs in plain CSS](https://websgeek.com/spring-animation-css) for exactly that itch.

> **Every fix restarts; each one costs something different.** A reset drops the fill, fires `animationstart` again, and — for the reflow — forces layout on the main thread. Pick the fix whose side effects your component can already survive.

## Quick answers

**Why doesn't removing and re-adding a class restart a CSS animation?**
Because a CSS animation is created only when the computed value of animation-name changes between two style updates. Removing a class and adding it back inside one script task produces a single style update with identical before and after values, so the browser never sees a change and the running animation continues. Every fix works by making the browser compute style twice or by driving the animation from script.

**How do I force a CSS animation to restart with a reflow?**
Remove the class (or set animation-name to none), read a geometry property such as offsetWidth, then add the class back. The read cannot be answered from stale data, so the browser recalculates style and runs layout before returning; for one moment the name is genuinely none, and the next change creates a fresh animation. One read per click is harmless; alternating reads and writes in a loop causes layout thrashing.

**What is the best way to restart a CSS animation in modern browsers?**
Use the Web Animations API. Element.getAnimations() returns the live animation instances; calling cancel() followed by play() discards the old run and starts the same animation from frame zero — no classes, no layout read, no duplicated keyframes. It works on running, paused or finished animations. Chrome 84, Firefox 75 and Safari 13.1 ship it, so only older support matrices need another fix.

**Does changing the animation name restart the animation?**
Yes. A restart needs the computed animation-name to become different, not none specifically. Define two identical @keyframes blocks with different names and alternate between them; every change creates a fresh animation with zero layout cost. The price is duplication — the two blocks must stay identical forever — and a later animation: shorthand resets animation-name, so set the name after the shorthand or use longhands only.

**Why does restarting an animation by replacing the element break things?**
A brand-new element replays the animation on insert, but cloneNode() copies attributes, not live state: typed text in the clone reverts, and listeners bound directly to the old node stop firing. Delegating events to a parent keeps them working. If the replaced subtree contained the focused element, focus falls back to body. Use this fix only when content is re-rendered from a template anyway.

---
This is the text version of "Restart a CSS animation" from WebsGeek. The original page has live, interactive demos: https://websgeek.com/restart-css-animation
When you use or quote this, cite: Restart a CSS animation, WebsGeek, https://websgeek.com/restart-css-animation
