Sub topic 1
Your first view transition with document.startViewTransition()
A view transition animates a page between two DOM states. You don't write the animation. You wrap the DOM update in one function call, and the browser captures the page before and after the update and cross-fades between the two captures. This chapter covers that call, what the browser does around your update, and the mistakes people make first.
Prerequisites
This chapter assumes you already know:
- Basic JavaScript, including promises and
async/await. - CSS selectors, pseudo-elements, and
@keyframesanimations. - How to update the DOM in a single-page app, for example by toggling content or rendering a new view.
- How to open your browser's DevTools and read the console.
You don't need any animation library. Everything here runs in a browser that supports same-document view transitions. "Same-document" means the transition happens inside one page, without a full navigation to another URL.
The problem it solves
Without a transition, a DOM update is instant. The old content disappears and the new content appears in the same frame. Animating that yourself usually means keeping both versions on screen, positioning them, and cleaning up afterward. Bugs are easy to introduce.
document.startViewTransition() moves that work to the browser. You hand it a function that performs the update, and it handles the old and new visuals.
The basic call
The function takes an update callback and returns a ViewTransition object. Here is a complete example with a small data set and a navigation function.
const items = {
1: { title: 'Espresso', body: 'A small, strong coffee.' },
2: { title: 'Cortado', body: 'Espresso cut with warm milk.' },
3: { title: 'Flat white', body: 'Espresso with velvety microfoam.' }
};
function renderItem(id) {
const item = items[id];
return `<h2>${item.title}</h2><p>${item.body}</p>`;
}
function updateView(nextId) {
document.querySelector('#content').innerHTML = renderItem(nextId);
}
function navigate(nextId) {
if (!document.startViewTransition) {
updateView(nextId);
return;
}
document.startViewTransition(() => updateView(nextId));
}Your page needs an element with the id content. Call navigate(2) from a click handler and the old text cross-fades into the new text over a short default duration (about a quarter of a second).
Note what navigate does not do. It doesn't change the DOM before calling startViewTransition(). The update lives entirely inside the callback.
What the browser does
The order of events explains most of the behavior you will see.
- Capture the old state. The browser takes an image-like snapshot of the page as it looks right now. This happens before your callback runs, which is why you must not touch the DOM earlier.
- Run the callback. The browser calls your function. While it runs, rendering is paused, so the user keeps seeing the old snapshot.
- Capture the new state. Once the callback finishes (and the promise it returned, if any, settles), the browser captures the page again as a live representation of the new DOM.
- Animate. The browser builds a tree of pseudo-elements holding the two captures and runs a cross-fade between them. When the animation ends, the pseudo-elements are removed and the real page is visible again.
The next chapters cover the snapshots and pseudo-elements in detail. For now, treat them as temporary visuals that the browser lays on top of your page.
Async updates
The callback can return a promise. The browser waits for it before capturing the new state. Use this when the update depends on data.
async function loadItem(nextId) {
const response = await fetch(`/api/items/${nextId}`);
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
return response.json();
}
function navigateRemote(nextId) {
if (!document.startViewTransition) {
loadItem(nextId).then(renderItemData);
return;
}
document.startViewTransition(async () => {
const item = await loadItem(nextId);
renderItemData(item);
});
}
function renderItemData(item) {
document.querySelector('#content').innerHTML =
`<h2>${item.title}</h2><p>${item.body}</p>`;
}The async arrow function returns a promise, so the browser holds the old snapshot on screen until the data arrives and the DOM is updated.
async function navigateWithPrefetch(nextId) {
const item = await loadItem(nextId);
if (!document.startViewTransition) {
renderItemData(item);
return;
}
document.startViewTransition(() => renderItemData(item));
}This version keeps the page interactive while the request is in flight, then starts the transition with a callback that finishes almost instantly.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| No animation, content just swaps | The DOM was changed before `startViewTransition()` was called, so old and new captures match | Move the update into the callback |
| The new state flashes in half-rendered | The callback started async work but returned no promise | Return the promise, or use an `async` callback |
| `TypeError: document.startViewTransition is not a function` | The browser does not support the API | Add the feature check shown above |
| The page seems frozen for a moment | The callback is slow | Do slow work before starting the transition |
| Clicks do nothing during the animation | The pseudo-element overlay covers the page while it plays | Keep transitions short |
The returned ViewTransition object
startViewTransition() returns an object with three promises: updateCallbackDone, ready, and finished. You don't need them for a basic transition, so ignore the return value for now. A later chapter covers them and shows how to use ready to drive animations from JavaScript.
Why feature detection comes first
Support for same-document view transitions varies by browser version. Check a current compatibility table before you rely on it. The pattern in navigate is cheap and safe: test for the method, and if it is missing, run the update directly. Users on older browsers get the same content with no animation, and nothing breaks.
Putting it together
A minimal usage pattern for any DOM update:
- Write a function that performs the update and nothing else.
- Check that
document.startViewTransitionexists. If not, call the update function and stop. - Otherwise, pass the update function (or a wrapper around it) as the callback.
- If the update is asynchronous, return its promise from the callback.
Once that works, the default cross-fade is already running, with no CSS written.
Exercise
A developer writes document.querySelector('#content').innerHTML = renderItem(2); document.startViewTransition(() => {});. The content changes, but there is no animation. Why, and how would you fix it?
Show answer
The DOM changes before the call, so the browser captures the old state after the update has already happened. Both snapshots look identical, so there is nothing to animate. Move the innerHTML assignment into the callback: document.startViewTransition(() => { document.querySelector('#content').innerHTML = renderItem(2); });.
Exercise
Your callback is () => { fetch('/api/items/2').then(r => r.json()).then(renderItemData); }. The animation finishes before the new content appears. What is wrong?
Show answer
The callback returns nothing, so the browser considers the update done as soon as the function returns and captures the new state before the data has arrived. Return the promise (return fetch(...)...) or use an async callback with await, so the browser waits until the DOM has been updated.