startViewTransition Crossfades DOM Updates

Wrap a DOM update in document.startViewTransition so the browser cross-fades old and new snapshots, honoring prefers-reduced-motion with a direct update.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
// document.startViewTransition snapshots the current DOM, runs the
// update callback, snapshots the result, and cross-fades the two —
// the animation itself comes from view transition pseudo-elements
const panel = document.querySelector('#panel');
const toggle = document.querySelector('#toggle');

toggle.addEventListener('click', () => {
  // Reduced motion: skip the transition and mutate directly
  if (matchMedia('(prefers-reduced-motion: reduce)').matches) {
    panel.classList.toggle('collapsed');
    return;
  }

  const transition = document.startViewTransition(() => {
    panel.classList.toggle('collapsed');
  });

  // finished resolves when the cross-fade completes or is skipped
  transition.finished.then(() => {
    console.log('panel collapsed:', panel.classList.contains('collapsed'));
  });
});

How the snippet works

Demo state sits in top-level bindings: panel, toggle.

Caveats

  • No package installation, no environment variables, no setup steps.
  • This is browser-side code — document will not resolve in Node.

Using it

Labels (panel collapsed:) ride along on the demo’s output, keeping line and origin connected.

Key statements

transition.finished.then(() => {
  console.log('panel collapsed:', panel.classList.contains('collapsed'));
});
const transition = document.startViewTransition(() => {
  panel.classList.toggle('collapsed');
});

Interactive Tools for This Topic

FAQ

Does startViewTransition Crossfades DOM Updates run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.