Sub topic 12
Animating transition pseudo-elements with JavaScript
CSS animations cover most view transitions. JavaScript is the better tool when the animation depends on runtime values, such as the pointer position, an element's measured size, or a sequence of steps. This chapter shows how to run your own animation on the transition pseudo-elements with the Web Animations API.
This chapter assumes you know document.startViewTransition(), the ::view-transition pseudo-element tree, and promises with async/await. It also assumes you know element.animate() or are willing to read a short example of it.
Why the ready promise matters
The pseudo-elements do not exist while your code is running. The browser builds them only after it captures the old state, runs your update callback, and captures the new state. The ready promise on the returned ViewTransition object resolves once the pseudo-element tree exists, just before the first animation frame.
| Promise | Resolves when | Rejects when |
|---|---|---|
| `updateCallbackDone` | The update callback's promise settles successfully | The callback throws or rejects |
| `ready` | The pseudo-elements are created and animation is about to start | The transition is skipped or the callback fails |
| `finished` | The animations end and the pseudo-elements are removed | The callback fails |
Animating before ready resolves has no effect, because there is no pseudo-element to target.
A first JavaScript animation
The animate() method accepts a pseudoElement option. Call it on the element the pseudo-element belongs to. For ::view-transition-new(root), that element is document.documentElement.
function updateView() {
document.querySelector('#content').textContent = new Date().toLocaleTimeString();
}
async function revealNext() {
if (!document.startViewTransition) {
updateView();
return;
}
const transition = document.startViewTransition(() => updateView());
try {
await transition.ready;
} catch (error) {
// The transition was skipped. The DOM update still ran.
return;
}
document.documentElement.animate(
{ clipPath: ['inset(0 0 100% 0)', 'inset(0)'] },
{
duration: 400,
easing: 'ease-in',
pseudoElement: '::view-transition-new(root)'
}
);
}The new snapshot sits on top of the old one. Its clip path starts at zero height and grows to full size, so the new view wipes in from the top over the old view.
The try/catch is not optional. If the browser skips the transition, ready rejects. Without a handler, you get an unhandled promise rejection in the console, even though the page itself works.
Switch off the default animation
The browser still applies its default cross-fade to the same pseudo-elements. The fade runs together with your clip-path reveal, so the result looks muddy. Remove the defaults in CSS:
::view-transition-old(root),
::view-transition-new(root) {
animation: none;
mix-blend-mode: normal;
}Two things change. animation: none removes the fade. mix-blend-mode: normal removes the browser's additive blending (plus-lighter) of the two snapshots, which would otherwise brighten any area where both are visible. With both rules in place, your JavaScript animation is the only motion on the page.
Example: a circular reveal from the click point
Because the animation runs in JavaScript, it can use values that CSS cannot know in advance. This example expands a circle from the pointer position, sized to reach the farthest corner of the viewport.
document.addEventListener('click', async (event) => {
if (!document.startViewTransition) {
toggleTheme();
return;
}
const { clientX: x, clientY: y } = event;
const radius = Math.hypot(
Math.max(x, window.innerWidth - x),
Math.max(y, window.innerHeight - y)
);
const transition = document.startViewTransition(() => toggleTheme());
try {
await transition.ready;
} catch {
return;
}
document.documentElement.animate(
{
clipPath: [`circle(0 at ${x}px ${y}px)`, `circle(${radius}px at ${x}px ${y}px)`]
},
{
duration: 500,
easing: 'ease-in-out',
pseudoElement: '::view-transition-new(root)'
}
);
});
function toggleTheme() {
document.documentElement.classList.toggle('dark');
}The Math.hypot call computes the distance from the click to the farthest corner. A smaller radius would leave part of the old view uncovered when the animation ends, and the page would then jump.
Animating more than one pseudo-element
You can call animate() several times in a row after ready. Each call targets one pseudo-element. For example, you can push the old snapshot back while the new one slides in:
await transition.ready;
document.documentElement.animate(
{ transform: ['translateX(0)', 'translateX(-20%)'], opacity: [1, 0] },
{ duration: 300, easing: 'ease-in', pseudoElement: '::view-transition-old(root)' }
);
document.documentElement.animate(
{ transform: ['translateX(100%)', 'translateX(0)'] },
{ duration: 300, easing: 'ease-out', pseudoElement: '::view-transition-new(root)' }
);The transition ends only after every animation on its pseudo-elements has finished. The longest animation therefore sets the transition's length. If one animation runs for 2 seconds, the page keeps its snapshot overlay for 2 seconds.
Common errors
- Animating before
ready. The call has nothing to target, so you see no motion. Alwaysawait transition.readyfirst. - Forgetting to catch
ready. A skipped transition rejects the promise. Wrap the await intry/catch. - Leaving the default animation on. The cross-fade stacks with your effect. Set
animation: noneon the old and new pseudo-elements you animate yourself. - Calling
animate()on the wrong element. Usedocument.documentElementfor the root tree. A pseudo-element belongs to the element that owns the tree, not to the named element inside it. - Using infinite iterations. An animation that never ends keeps the transition alive, and the page stays covered by snapshots and cannot be clicked.
- Ignoring reduced motion. JavaScript animations are not covered by a CSS media query that targets the pseudo-elements, unless you also disable them there. Check
matchMediayourself.
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (!prefersReducedMotion) {
document.documentElement.animate(
{ clipPath: ['inset(0 0 100% 0)', 'inset(0)'] },
{ duration: 400, pseudoElement: '::view-transition-new(root)' }
);
}When to choose JavaScript over CSS
Use CSS keyframes when the animation is fixed and the same for every user. Use JavaScript when you need runtime values, such as a click position or a measured distance, or when you want to build the keyframes in code. The Web Animations API also gives you an Animation object, so you can pause, reverse, or read progress on it.
Exercise
A developer calls document.documentElement.animate({ opacity: [0, 1] }, { duration: 300, pseudoElement: '::view-transition-new(root)' }) on the line right after document.startViewTransition(updateView). Nothing animates. What are the two fixes needed for this to work reliably?
Show answer
First, wait for the pseudo-elements to exist by calling the animation after await transition.ready, because they are created only after the update callback runs and the new state is captured. Second, wrap that await in try/catch, because ready rejects if the transition is skipped. Also set animation: none on ::view-transition-new(root) in CSS if the default fade should not run alongside the custom one.
Exercise
You animate ::view-transition-old(root) for 300 ms and ::view-transition-new(root) for 1200 ms. How long does the transition last, and why?
Show answer
About 1200 ms. The transition finishes only when all animations on its pseudo-elements have ended, so the longest one sets the duration. The page stays covered by snapshots until then.