Sub topic 9
Hooking in with pageswap and pagereveal
This chapter covers the two page events that let JavaScript take part in a cross-document view transition. It assumes you can already turn transitions on with @view-transition { navigation: auto }, name elements with view-transition-name, and write ::view-transition-old() and ::view-transition-new() rules. You also need basic JavaScript event listeners and the URL object.
Why CSS alone is not enough
A CSS rule applies to every navigation in the same way. It cannot tell whether the user is going from a list to a post or from a post back to the list. It also cannot pick one thumbnail out of twenty as the element that should morph.
Those decisions depend on the source URL, the destination URL, and the page contents. JavaScript has to make them. The browser gives you two events, one on each side of the navigation.
The two events
| Event | Fires on | When | What it is for |
|---|---|---|---|
| `pageswap` | The old page | Just before the old page is replaced, after the browser decides to run a transition | Change the old page's state before its snapshot is taken |
| `pagereveal` | The new page | After the new page is initialized, before its first rendering opportunity | Change the new page's state before the transition starts |
Both events carry a viewTransition property. It is a ViewTransition object when a transition will run, and null when none will. Always check it first, because the events also fire on navigations that do not get a transition.
pageswap also has an activation property. It is a NavigationActivation object that describes the navigation, and activation.entry.url is the destination URL. On the new page, pagereveal has no event-level activation object. Read window.navigation.activation instead. Its from entry gives the previous page's URL, and its entry gives the current one.
Some details to keep in mind:
event.activationcan benullonpageswap, for example when the navigation is cross-origin. Test for it.navigation.activation.fromcan benull, for example on a first load or after a reload. Test for it.- Both events are only dispatched for same-origin navigations that actually have a transition.
The sequence
The following diagram shows where each handler runs relative to the snapshots.
The key point is timing. Anything you set in pageswap appears in the old snapshot. Anything you set in pagereveal appears in the new snapshot. Names must match across the two sides to be paired.
Naming a shared element: list to detail
Suppose a blog list page shows cards. Each card has a thumbnail, and each post page has a hero image. You want the clicked thumbnail to grow into the hero.
You cannot hard-code view-transition-name: post-image on every thumbnail. Names must be unique within a page. If two elements share a name when the snapshot is taken, the transition is skipped. So you assign the name only to the thumbnail that was clicked.
The post page needs no JavaScript for this. Its hero image has a fixed name in CSS:
.post-hero img {
view-transition-name: post-image;
}The list page tags the clicked thumbnail in pageswap:
window.addEventListener('pageswap', (event) => {
if (!event.viewTransition || !event.activation) return;
const to = new URL(event.activation.entry.url);
const match = to.pathname.match(/^\/posts\/([^/]+)\/?$/);
if (!match) return;
const thumb = document.querySelector(`[data-post="${CSS.escape(match[1])}"] img`);
if (thumb) thumb.style.viewTransitionName = 'post-image';
});Walk through it line by line:
- The guard returns early if no transition will run or if the destination is unknown.
new URL(...)parses the destination so you can read its path.- The regular expression accepts only
/posts/<slug>and captures the slug. CSS.escapemakes the slug safe to put inside an attribute selector.- The matching thumbnail gets the name
post-image, so the old snapshot pairs it with the hero on the new page.
The name is set inline and never removed. That is fine here, because the old page is about to be discarded.
Going back: tagging on pagereveal
The reverse trip needs the opposite setup. The post page's hero has the name, and the list page must give the same name to the right thumbnail. On the list page, that work happens in pagereveal:
window.addEventListener('pagereveal', async (event) => {
if (!event.viewTransition) return;
const from = window.navigation?.activation?.from;
if (!from) return;
const match = new URL(from.url).pathname.match(/^\/posts\/([^/]+)\/?$/);
if (!match) return;
const thumb = document.querySelector(`[data-post="${CSS.escape(match[1])}"] img`);
if (!thumb) return;
thumb.style.viewTransitionName = 'post-image';
await event.viewTransition.finished;
thumb.style.viewTransitionName = 'none';
});Here the name is removed after the transition. This matters because the list page stays open. If post-image stayed on one thumbnail, the next click would set it on a second thumbnail, and two elements would carry the same name. The transition would then be skipped. Setting the value to none clears it.
event.viewTransition.finished is a promise that settles when the animation ends or is skipped. Awaiting it is the standard cleanup point.
You can put both handlers in one shared script that every page loads. Each handler returns early when its URL pattern does not match, so the same file is safe on all pages.
Setting transition types
The same events can label a transition with a type. A type is a string that CSS can test, so you can choose a different animation for each direction. Add it in pageswap:
window.addEventListener('pageswap', (event) => {
if (!event.viewTransition || !event.activation) return;
const to = new URL(event.activation.entry.url);
event.viewTransition.types.add(
to.pathname.startsWith('/posts/') ? 'forward' : 'back'
);
});types behaves like a Set, so use add, delete, and has. CSS then reacts with :active-view-transition-type():
@view-transition {
navigation: auto;
}
html:active-view-transition-type(forward)::view-transition-old(root) {
animation: 250ms ease-in both slide-out;
}
html:active-view-transition-type(back)::view-transition-new(root) {
animation: 250ms ease-out both slide-in;
}The next chapters in this tutorial cover types in more detail. For now, note that the type is read from the type set on the page that is currently being animated, and the new page also sees the types the old page added.
A rule of thumb for choosing the event:
- Use
pageswapwhen the choice depends on where the user is going, and the old page's contents. - Use
pagerevealwhen the choice depends on where the user came from, and the new page's contents. - Use either for types, as long as you are consistent. You can also add types in
pagerevealthroughevent.viewTransition.types.
Edge cases and gotchas
- Both events fire without a transition. A cross-origin link, a browser without the feature, or a skipped transition leaves
event.viewTransitionasnull. Without the guard, your code runs for no reason or throws. pageswaphandlers must be fast. The browser waits for them before it captures the old snapshot. Do not fetch data or wait on promises there. Keep the work to reading the URL and setting a style.- Duplicate names skip the transition. If two elements share a
view-transition-namewhen a snapshot is captured, the whole transition is skipped. This is the most common failure after adding dynamic names. - Names set in
pagerevealmust be set before rendering. The handler runs before the first render, so synchronous changes are included. If youawaitsomething before setting the name, the transition may already have captured the new state. - Back and forward navigations count. The history buttons fire both events too. That is why the list page needs the
pagerevealhandler and not onlypageswap. - The bfcache can restore a page. A page restored from the back/forward cache does not fire
pagerevealas a fresh load. If you depend on that event for setup, test with a restored page. - Escape untrusted values. The slug comes from a URL.
CSS.escapestops a crafted path from breaking out of the attribute selector.
Feature detection
These events exist only in browsers that support cross-document view transitions. Registering a listener for an event the browser never fires is harmless, so you do not need a guard around addEventListener. Inside the handlers, the viewTransition check already covers unsupported cases. Use optional chaining, as in window.navigation?.activation?.from, for APIs that may be missing.
Exercise
A list page tags the clicked thumbnail with view-transition-name: post-image in a pageswap handler. Going back, the transition is skipped on the second visit to the list page, though it works the first time. The pagereveal handler sets the same name on the matching thumbnail but never clears it. What is the likely cause, and how do you fix it?
Show answer
After the first round trip, the thumbnail keeps the inline name post-image. On the next navigation, the pageswap handler names a second thumbnail, so two elements share the name when the snapshot is captured, and the browser skips the transition. Fix it by awaiting event.viewTransition.finished in pagereveal and then setting thumb.style.viewTransitionName = 'none'.
Exercise
Which URL do you read to find the previous page inside a pagereveal handler, and why do you need a null check on it?
Show answer
Read window.navigation.activation.from.url. The from entry is null when there was no earlier same-origin entry, such as on a first load or after a reload, so you must check it before reading url.