Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readCSS

Cross-fade a same-document view transition

Cross-fade an order list and a detail pane with startViewTransition, and keep the same DOM update for browsers and readers who skip motion.

You click into an order and the list turns into a detail pane in one frame. A cross-fade can make that swap easier to follow. Give the browser the DOM update and let it handle the two views.

Put the DOM change inside the callback

document.startViewTransition(update) runs the update after capturing the old view. Use the same function for the direct update when the API is missing or the reader prefers reduced motion.

Save this as an HTML file and open it in a browser.

<button type="button" id="switch">Switch view</button>
<section id="panel">Order list</section>
<script>
  const panel = document.querySelector('#panel')
  document.querySelector('#switch').addEventListener('click', () => {
    const update = () => {
      panel.textContent = panel.textContent === 'Order list'
        ? 'Order #42' : 'Order list'
    }

    if (!document.startViewTransition ||
        matchMedia('(prefers-reduced-motion: reduce)').matches) {
      update()
      return
    }
    document.startViewTransition(update)
  })
</script>

The button switches between Order list and Order #42, with a cross-fade when the transition runs.

The button sits outside the part of the DOM that changes. It keeps focus as the order text changes, so you can press it again without finding a new control. The page stays at the same URL.

Follow the two captures

The View Transitions spec puts the update between the old and new captures. If you change the DOM before calling startViewTransition, the first capture can already contain the detail pane.

diagram

One DOM update between two captures

The browser captures Order list before the callback swaps in Order #42.

The default root animation fades the old view out and the new view in. To change its duration, target ::view-transition-old(root) and ::view-transition-new(root) in CSS.

Keep network work outside the callback. The browser waits for the callback's promise before it captures the new view, so a slow order request can hold up the switch. Fetch the order first and pass the browser a callback that can render the data it already has.

If the DOM changes but you see no fade, check reduced motion and API support first. For a custom animation, check the transition object's ready promise for a rejection. Test the direct-update path with reduced motion enabled. It should show the same order text and keep the same button usable.