Sub topic 1
Your First View Transition with `document.startViewTransition()`
Prerequisites
Assume you know basic JavaScript, promises, async/await, CSS selectors, @keyframes, and how a single-page app updates the DOM.
Start a View Transition
A same-document view transition animates one DOM state into another. Pass the DOM update to document.startViewTransition():
function updateView(nextId) {
document.querySelector("#content").innerHTML = renderItem(nextId);
}
function navigate(nextId) {
if (!document.startViewTransition) {
updateView(nextId);
return;
}
document.startViewTransition(() => updateView(nextId));
}The callback must perform the update synchronously. The browser uses the DOM before and after that callback to create the transition.
What the Browser Does
The browser follows this sequence:
- Captures a visual snapshot of the current page.
- Runs the update callback.
- Captures a snapshot of the updated page.
- Animates between the snapshots.
The update callback still changes the real DOM. The snapshots provide the visual layers used during the animation.
The Pseudo-Element Tree
The browser exposes transition layers through special CSS pseudo-elements:
::view-transitionis the transition container.::view-transition-group(root)controls the root transition.::view-transition-image-pair(root)contains the old and new images.::view-transition-old(root)represents the previous snapshot.::view-transition-new(root)represents the updated snapshot.
These pseudo-elements are not ordinary DOM nodes. You can select them in CSS, but you cannot query them with querySelector().
The Default Cross-Fade
By default, the old snapshot fades out while the new snapshot fades in. Both layers may briefly blend, producing a cross-fade.
Customize the Animation with CSS
Target the old and new root images to replace the default timing and easing:
@keyframes fade-out {
to { opacity: 0; }
}
@keyframes fade-in {
from { opacity: 0; }
}
::view-transition-old(root) {
animation: 300ms ease-out both fade-out;
}
::view-transition-new(root) {
animation: 300ms ease-in both fade-in;
}Exercise
Where should the DOM update occur when using document.startViewTransition()?
Show answer
Inside the callback passed to document.startViewTransition(), with a feature-detection fallback for unsupported browsers.