Sub topic 3
Hooking In with `pageswap` and `pagereveal`
Assume you know HTML, CSS animations, multi-page navigation, and basic JavaScript event listeners. Cross-document view transitions expose two useful lifecycle events:
pageswapruns on the page being left, before its snapshot is taken.pagerevealruns on the page being opened, before its snapshot is revealed.
Both events provide event.viewTransition when a transition is active. Check this property before changing transition behavior.
window.addEventListener("pageswap", (event) => {
if (!event.viewTransition || !event.activation) return;
const destination = new URL(event.activation.entry.url);
event.viewTransition.types.add(
destination.pathname.startsWith("/posts/") ? "forward" : "back"
);
});
window.addEventListener("pagereveal", async (event) => {
if (!event.viewTransition) return;
// Keep the page available while its transition finishes.
await event.viewTransition.finished;
});Naming Elements per Navigation
A shared element needs the same unique view-transition-name on both pages. For a list-to-detail transition, name only the thumbnail that was clicked. Assigning the name in pageswap avoids giving multiple list items the same name.
window.addEventListener("pageswap", (event) => {
if (!event.viewTransition || !event.activation) return;
const url = new URL(event.activation.entry.url);
const match = url.pathname.match(/^\/posts\/([^/]+)\/?$/);
if (!match) return;
const image = document.querySelector(
`[data-post="${CSS.escape(match[1])}"] img`
);
if (image) image.style.viewTransitionName = "post-image";
});The detail page’s hero image must also use view-transition-name: post-image. A unique name prevents unrelated elements from being matched.
Directional Animations with Transition Types
CSS can select a transition type:
html:active-view-transition-type(forward)::view-transition-old(root) {
animation: 200ms ease-in both slide-out;
}
html:active-view-transition-type(back)::view-transition-new(root) {
animation: 200ms ease-out both slide-in;
}Waiting, Debugging, and Performance
Use <link rel="expect" href="#main" blocking="render"> when critical content must exist before the new snapshot. In DevTools, inspect the View Transitions or Animations panel and verify the pseudo-elements, names, and event timing.
Keep snapshots small. Avoid naming large containers, duplicate names, or animating expensive layout properties. Prefer opacity and transform. Respect reduced motion:
@media (prefers-reduced-motion: reduce) {
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation: none !important;
}
}Exercise
Why should a list page assign a shared element name during pageswap instead of naming every thumbnail permanently?
Show answer
Only the selected thumbnail should match the detail image. Permanent duplicate names make the transition ambiguous and can prevent it from running.