Sub topic 11
Directional animations with transition types
A single slide animation looks wrong half the time. Opening a post should move the page forward. Returning to the list should move it back. This chapter shows how to label each navigation with a transition type. CSS then picks a different animation for each label.
You should already know how to enable cross-document transitions with @view-transition, how ::view-transition-old(root) and ::view-transition-new(root) work, and how the pageswap and pagereveal events fire. The earlier chapters cover all of that.
The problem with one animation for every navigation
Suppose your CSS styles ::view-transition-old(root) to slide left and ::view-transition-new(root) to slide in from the right. That animation reads as "going deeper". It looks wrong when the user presses Back, because the page should move the other way.
CSS alone cannot tell these navigations apart. It does not know which URL you came from or whether the user clicked a link or pressed Back. Your JavaScript knows, through the lifecycle events. A transition type is how it passes that knowledge to CSS.
What a transition type is
A transition type is a short string, such as forward or back. It is attached to one view transition. Each ViewTransition object has a types property, which is a set-like collection of strings. While the transition runs, CSS can match its types with the :active-view-transition-type() pseudo-class.
html:active-view-transition-type(forward) {
/* matches only while a transition with the type "forward" is running */
}The pseudo-class matches the root element, so you write html:active-view-transition-type(...) or :root:active-view-transition-type(...). You then append the pseudo-element you want to style. Type names are arbitrary identifiers that you choose. The browser gives them no meaning.
You can match several types at once by separating them with commas, for example :active-view-transition-type(forward, back).
Types are per document
Each page involved in a cross-document transition has its own ViewTransition object. The old page's object is exposed on pageswap. The new page's object is exposed on pagereveal. A type added in one document is not carried to the other.
This matters because each document runs its own CSS. The old page's stylesheet animates ::view-transition-old(root). The new page's stylesheet animates ::view-transition-new(root). If you add forward only in pageswap, the new page never sees it, and the animation on the new snapshot falls back to the default. To animate both sides in the same direction, add the type in both events.
| Event | Runs in | Where to read the URLs | Styles affected |
|---|---|---|---|
| `pageswap` | The page being left | `location` is the old URL. `event.activation.entry.url` is the destination. | Old page's CSS, usually `::view-transition-old(root)` |
| `pagereveal` | The page being opened | `location` is the new URL. `navigation.activation.from.url` is the origin. | New page's CSS, usually `::view-transition-new(root)` |
Both events expose event.viewTransition. It is null when no transition will run, so always check it first.
Deciding the direction in JavaScript
Pick a rule that matches how your site is organized. This example treats /posts/... as deeper than everything else. Going from a non-post page to a post is forward. Going from a post to a non-post page is back. Navigation between two pages of the same kind gets no type.
Put this script in a file that every page loads.
function directionFor(fromPath, toPath) {
const fromPost = fromPath.startsWith('/posts/');
const toPost = toPath.startsWith('/posts/');
if (!fromPost && toPost) return 'forward';
if (fromPost && !toPost) return 'back';
return null;
}
// Old page: runs just before it is replaced.
window.addEventListener('pageswap', (event) => {
if (!event.viewTransition || !event.activation) return;
const toPath = new URL(event.activation.entry.url).pathname;
const direction = directionFor(location.pathname, toPath);
if (direction) event.viewTransition.types.add(direction);
});
// New page: runs before the first frame is rendered.
window.addEventListener('pagereveal', (event) => {
if (!event.viewTransition) return;
const from = window.navigation?.activation?.from;
if (!from) return;
const fromPath = new URL(from.url).pathname;
const direction = directionFor(fromPath, location.pathname);
if (direction) event.viewTransition.types.add(direction);
});Two details are easy to miss:
window.navigationis the Navigation API. Some browsers that support view transitions have not shipped it, so the optional chaining (?.) is required. Iffromis missing, the new page adds no type and falls back to the default animation.- Both handlers compute the direction from the same rule, so the two documents agree. Keep that rule in one shared function. If the two copies drift apart, one page animates forward while the other animates back.
Styling each direction
With the types in place, write one rule set per direction. A forward navigation moves the old page out to the left and brings the new page in from the right. A back navigation reverses both.
@view-transition {
navigation: auto;
}
@keyframes to-left {
to { opacity: 0; transform: translateX(-40px); }
}
@keyframes from-right {
from { opacity: 0; transform: translateX(40px); }
}
@keyframes to-right {
to { opacity: 0; transform: translateX(40px); }
}
@keyframes from-left {
from { opacity: 0; transform: translateX(-40px); }
}
html:active-view-transition-type(forward)::view-transition-old(root) {
animation: 200ms ease-in both to-left;
}
html:active-view-transition-type(forward)::view-transition-new(root) {
animation: 300ms ease-out both from-right;
}
html:active-view-transition-type(back)::view-transition-old(root) {
animation: 200ms ease-in both to-right;
}
html:active-view-transition-type(back)::view-transition-new(root) {
animation: 300ms ease-out both from-left;
}
@media (prefers-reduced-motion: reduce) {
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation: none !important;
}
}Navigations with no type match none of the directional rules, so they keep the browser's default crossfade. That is a useful default. You only write rules for the cases you want to treat specially.
The reduced-motion block comes last and uses !important, so it wins over the directional rules regardless of specificity. Motion preferences are covered in their own chapter. Keep this block with your direction rules so the two cannot be separated by accident.
Using the real history direction
The URL rule above works when your site has a clear hierarchy. Sometimes you want the true direction through the browser's history instead. If the user presses Back, the animation should run backward whatever the URLs look like.
event.activation.navigationType is one of push, replace, reload, or traverse. A traverse is a Back or Forward move. For traversals you can compare history indexes:
window.addEventListener('pageswap', (event) => {
if (!event.viewTransition || !event.activation) return;
const { from, entry, navigationType } = event.activation;
if (navigationType === 'traverse' && from && entry) {
event.viewTransition.types.add(entry.index < from.index ? 'back' : 'forward');
} else if (navigationType === 'push') {
event.viewTransition.types.add('forward');
}
});Add the matching logic to pagereveal, using window.navigation.activation. It has the same from, entry, and navigationType fields. The rule to follow stays the same: both documents must apply the same rule.
Types you can combine
A transition can carry more than one type. Use that to separate independent concerns. For example, add forward for direction and hero when the navigation involves a shared image. Each CSS rule then matches only the types it needs.
html:active-view-transition-type(forward):not(:active-view-transition-type(hero))::view-transition-old(root) {
animation: 200ms ease-in both to-left;
}Keep the type vocabulary small. Every type you add is one more string that both documents must agree on.
Skipping a transition
Types change how a transition looks. If you want no transition at all for some navigations, call skipTransition() on the ViewTransition in pageswap:
window.addEventListener('pageswap', (event) => {
if (!event.viewTransition) return;
if (location.pathname === new URL(event.activation.entry.url).pathname) {
event.viewTransition.skipTransition();
}
});This stops a transition when the user navigates to the same path, for example by clicking a link to the current page.
Common errors
- Only one side animates in the right direction. The type was added in only one event. Add it in both
pageswapandpagereveal. - The default crossfade always runs. Your selector does not match. Check that the pseudo-class is on
html, that the type spelling is identical in JavaScript and CSS, and that the stylesheet is loaded on both pages. - Nothing happens on Back. The old page's
pageswapmay have noevent.activationor noevent.viewTransition. The guards return early, so your handler adds no type. Log the values to confirm. - Types added too late. Add them synchronously, or soon after, inside the event handler. Once the transition has started animating, a late
types.add()has no effect on the rules that were already matched. - Unsupported browsers throw errors. Guard Navigation API access with
window.navigation?.and exit early whenevent.viewTransitionis missing.
Summary
Use a transition type when one animation cannot suit every navigation. Compute a direction in pageswap and pagereveal with one shared function. Add it with viewTransition.types.add() in both documents. Match it in CSS with :active-view-transition-type(). Navigations that carry no type keep the default animation, and the reduced-motion block turns the motion off for users who ask for that.
Exercise
A list page has pageswap and pagereveal handlers that add the type forward. The CSS styles html:active-view-transition-type(forward)::view-transition-old(root) and ::view-transition-new(root). On the post page you load the CSS but forget to include the script with the pagereveal handler. What do you see on a forward navigation, and why?
Show answer
The old page slides out using the forward rule, but the new page fades in with the default animation. Types are per document. The old page's ViewTransition has forward, so its ::view-transition-old(root) rule matches. The new page's ViewTransition has no types because its pagereveal handler never ran, so the ::view-transition-new(root) rule does not match. The fix is to load the same script on both pages.
Exercise
Write the condition that adds back in pageswap only when the user pressed the browser Back button, given event.activation with from, entry, and navigationType.
Show answer
if (event.activation.navigationType === 'traverse' && event.activation.entry.index < event.activation.from.index) { event.viewTransition.types.add('back'); }. A traverse is a Back or Forward move, and a lower destination index than the origin index means the user went back in history.