Sub topic 15
Choosing animations with transition types
This chapter assumes you can call document.startViewTransition(), style the ::view-transition-old(root) and ::view-transition-new(root) pseudo-elements, and read a promise chain. Earlier chapters covered all three.
The problem types solve
A view transition runs the same CSS every time. Suppose you build a paged interface. Moving to the next page should slide content left, and moving back should slide it right. A single ::view-transition-old(root) rule can't do both.
A common workaround is to set a class or data- attribute on <html> before the transition starts and remove it afterward. This works, but you must clean it up on every path: when the transition finishes, is skipped, or throws. Transition types are the built-in version of this pattern. You attach one or more strings to a transition, and CSS can match those strings only while that transition is active. The browser clears them when the transition ends.
Passing types to startViewTransition()
Instead of a bare callback, pass an object with update and types:
document.startViewTransition({
update: () => updateView(),
types: ['slide-forward']
});update is the same callback you already know. types is an array of strings. The names are yours to choose, and they are case-sensitive. They must be valid CSS identifiers, because you will match them in a selector.
Matching types in CSS
The :active-view-transition-type() pseudo-class matches the root element while a transition carrying that type is running. Combine it with the pseudo-element selectors to scope an animation to one type:
@keyframes slide-out-left { to { transform: translateX(-40px); opacity: 0; } }
@keyframes slide-in-right { from { transform: translateX(40px); opacity: 0; } }
@keyframes slide-out-right { to { transform: translateX(40px); opacity: 0; } }
@keyframes slide-in-left { from { transform: translateX(-40px); opacity: 0; } }
html:active-view-transition-type(slide-forward)::view-transition-old(root) {
animation: 250ms ease-in both slide-out-left;
}
html:active-view-transition-type(slide-forward)::view-transition-new(root) {
animation: 250ms ease-out both slide-in-right;
}
html:active-view-transition-type(slide-back)::view-transition-old(root) {
animation: 250ms ease-in both slide-out-right;
}
html:active-view-transition-type(slide-back)::view-transition-new(root) {
animation: 250ms ease-out both slide-in-left;
}If a transition has no types, or none of these, the rules don't match. The browser then uses the default cross-fade or whatever unscoped rules you wrote. That makes types a good layer on top of a baseline animation.
A complete direction-aware example
This script picks the type from the direction of navigation. The page content is plain text so the example runs as written.
const pages = ['Intro', 'Setup', 'Usage', 'Limits'];
let current = 0;
function updateView() {
document.querySelector('#content').textContent = pages[current];
}
function goTo(nextIndex) {
if (nextIndex < 0 || nextIndex >= pages.length) return;
const type = nextIndex > current ? 'slide-forward' : 'slide-back';
current = nextIndex;
if (!document.startViewTransition) {
updateView();
return;
}
document.startViewTransition({ update: updateView, types: [type] });
}
document.querySelector('#next').addEventListener('click', () => goTo(current + 1));
document.querySelector('#prev').addEventListener('click', () => goTo(current - 1));
updateView();The indexated before the call, and updateView reads it. This keeps the update callback free of navigation logic, so the same function can render the first view without a transition.
Reading and changing types through the ViewTransition object
The object returned by startViewTransition() has a types property. It behaves like a Set of strings, so you can use add(), delete(), has(), and clear():
const transition = document.startViewTransition(() => updateView());
transition.types.add('slide-forward');This is useful when the right type isn't known until the update runs. For example, a router may resolve the destination inside the callback. Add the type from inside the callback, before the new state is captured:
const transition = document.startViewTransition(async () => {
const route = await loadRoute(url);
updateView(route);
transition.types.add(route.depth > currentDepth ? 'slide-forward' : 'slide-back');
});Here loadRoute, route.depth, and currentDepth stand for your own router code. The key point is that types can change until the animation starts. Once the browser begins animating, changes have no effect on which rules were chosen at that moment.
Using several types at once
A transition can carry more than one type, and each type can answer a different question. One might describe direction, and another might describe what triggered the change:
document.startViewTransition({
update: () => updateView(),
types: ['slide-forward', 'keyboard']
});The pseudo-class accepts a comma-separated list and matches if any listed type is active. You can also chain several pseudo-classes to require all of them:
/* Matches either type */
html:active-view-transition-type(slide-forward, slide-back)::view-transition-group(root) {
animation-duration: 250ms;
}
/* Matches only when both are active */
html:active-view-transition-type(slide-forward):active-view-transition-type(keyboard)::view-transition-group(root) {
animation-duration: 120ms;
}Keep the vocabulary small. Every type becomes part of your CSS contract, and unused types are easy to leave behind.
Types and reduced motion
Types choose which animation runs. They don't decide whether motion is appropriate. Keep the prefers-reduced-motion rule from the earlier chapter, and make sure it wins over your type-scoped rules. A selector like html:active-view-transition-type(slide-forward)::view-transition-old(root) has higher specificity than ::view-transition-old(*) because of the added type and element selectors. That means the earlier reduced-motion rule may lose even with !important absent. The earlier rule used !important, which is why it stays safe. If you remove !important, repeat the media query with matching specificity.
Support and fallback
Transition types are newer than startViewTransition() itself. A browser can support the basic API without supporting the options object. In that case, passing an object where it expects a function can throw a TypeError, and the DOM update would not run. Guard the call:
const supportsTypes =
typeof ViewTransition !== 'undefined' && 'types' in ViewTransition.prototype;
function transitionWithType(type, update) {
if (!document.startViewTransition) {
update();
return;
}
if (supportsTypes) {
document.startViewTransition({ update, types: [type] });
} else {
document.startViewTransition(update);
}
}In the CSS, an unknown pseudo-class invalidates the whole rule it appears in, so the browser ignores those rules and uses the default cross-fade. That is the fallback you want. If you need to detect support in CSS, use @supports selector(:active-view-transition-type(x)).
Common mistakes
- Putting the types array on the wrong argument. The array goes in the options object, not as a second argument to
startViewTransition(). - Matching a type on the wrong element. The pseudo-class matches the root element. Write
html:active-view-transition-type(...)or:root:active-view-transition-type(...), and then add the pseudo-element. - Expecting types to persist. They are cleared when the transition ends. Don't read
transition.typesafterfinishedresolves. - Typos in names. A type that matches nothing causes no error. The default animation runs, and the bug is easy to miss. Define type names as constants in JavaScript.
- Forgetting the same-document scope. Everything here applies to same-document transitions. Cross-document navigations can also carry types, but they are set in the
pageswapandpagerevealevents, which this chapter does not cover.
Exercise
A gallery has an "Open" action that should zoom into a detail view, and a "Close" action that should zoom out. A developer writes document.startViewTransition(() => showDetail(), ['zoom-in']) and the CSS rules for zoom-in never apply. What is wrong, and how do you fix it?
Show answer
The types array is passed as a second argument, which startViewTransition() ignores. Types belong in an options object: document.startViewTransition({ update: () => showDetail(), types: ['zoom-in'] }). The CSS must also match the root, for example html:active-view-transition-type(zoom-in)::view-transition-new(root).
Exercise
Why should you wrap the options-object call in a support check instead of relying only on if (!document.startViewTransition)?
Show answer
A browser can implement startViewTransition() with only the callback form. Passing an options object there can throw, so the DOM update would not run. Checking that 'types' in ViewTransition.prototype lets you fall back to startViewTransition(update) or a plain update.