Sub topic 10
Naming elements per navigation (list to detail)
This chapter assumes you have read the earlier chapters. You should know how to opt in with @view-transition, what the ::view-transition-* pseudo-elements are, and how a static view-transition-name pulls an element out of the root snapshot. You should also be comfortable with addEventListener and querySelector.
The problem a list page creates
A blog index shows many cards, each with a thumbnail. Each post page has one large hero image. You want the clicked thumbnail to grow into the hero image. The browser can only do that if it finds one element with the name post-image in the old page and one with the same name in the new page.
The obvious fix is to put the name in the stylesheet:
.card img {
view-transition-name: post-image; /* wrong for a list */
}This breaks the list page. Every card now has the same name, but a name must be unique within one page state. When the browser finds duplicates while capturing, it skips the whole transition. You get a normal, unanimated navigation, and DevTools or the console reports the duplicate name.
Giving each card its own name (post-image-1, post-image-2, and so on) does not work either. The detail page has to use the same name as the card, so its CSS would need to know which post it is showing. You would also be creating dozens of named elements that never take part in a transition.
The solution is to name only the one element that matters, and to do it at navigation time.
Which page does what
Two events give you the hook points. The previous chapter covered them in general. Here is the part each one plays in a list-to-detail flow.
pageswapfires on the page being left, just before its final state is captured. Itsevent.activation.entry.urltells you where you are going. Use it to name the clicked thumbnail.pagerevealfires on the page being shown, before its first render. Itsnavigation.activation.from.urltells you where you came from. Use it to name the matching thumbnail when the user returns to the list.
The detail page needs neither event for the hero image. It has one hero, so a static rule is enough.
.post-hero img {
view-transition-name: post-image;
}The static rule on the detail page and the dynamic assignment on the list page are two halves of one pair.
Naming the outgoing thumbnail
Assume this markup on the list page, where each card carries its post slug:
<article class="card" data-post="intro-to-css">
<a href="/posts/intro-to-css/">
<img src="/img/intro-to-css-thumb.jpg" alt="A laptop showing CSS code">
<h2>Intro to CSS</h2>
</a>
</article>The pageswap handler finds the destination URL, extracts the slug, and names the thumbnail for that slug.
// Shared helper: return the post slug for a /posts/<slug>/ URL, or null.
function postSlug(url) {
const match = new URL(url).pathname.match(/^\/posts\/([^/]+)\/?$/);
return match ? match[1] : null;
}
function thumbFor(slug) {
return document.querySelector(`[data-post="${CSS.escape(slug)}"] img`);
}
window.addEventListener('pageswap', (event) => {
if (!event.viewTransition || !event.activation) return;
const slug = postSlug(event.activation.entry.url);
if (!slug) return;
const thumb = thumbFor(slug);
if (thumb) thumb.style.viewTransitionName = 'post-image';
});Each guard has a reason:
event.viewTransitionisnullwhen no transition will run. Examples are a cross-origin navigation, a missing opt-in, or a browser that decided to skip. Setting names then would do nothing useful.event.activationcan benulltoo, so check it before readingentry.postSlugreturnsnullfor any URL that is not a post, such as/about/. Those navigations keep the default root animation with no shared element.CSS.escapeprotects the attribute selector if a slug ever contains quotes, brackets, or other special characters. Treat anything derived from a URL as untrusted text when you build a selector from it.
The name has to be set inside the pageswap handler. The browser captures the old state right after the event, so a name set later is too late.
Naming the incoming thumbnail on the way back
When the user presses Back, the roles flip. The detail page, with its static hero name, is the old state. The list page loads fresh and is the new state. Nothing has named any thumbnail on that fresh page, so you do it in pagereveal.
window.addEventListener('pagereveal', async (event) => {
if (!event.viewTransition) return;
const from = window.navigation?.activation?.from;
if (!from) return;
const slug = postSlug(from.url);
if (!slug) return;
const thumb = thumbFor(slug);
if (!thumb) return;
thumb.style.viewTransitionName = 'post-image';
await event.viewTransition.finished;
thumb.style.viewTransitionName = 'none';
});Three details matter here:
window.navigation?.activation?.fromuses optional chaining because the Navigation API is not present in every browser that supports view transitions. If it is missing, the handler returns and you get the root animation without the shared element.pagerevealruns before the first render, so a name set here is included in the new-state capture.- Awaiting
event.viewTransition.finishedand then resetting the name removes the thumbnail from the named-element set once the animation ends. A leftover name keeps the element as its own stacking context and capture target, and it can collide with a name you assign on the next navigation.
The list page also runs pagereveal on a first visit, such as a direct link or a reload. In that case from is null or points to a non-post URL, and the handler exits early.
Clearing stale names after back-forward cache restores
A page can be stored in the back-forward cache (bfcache) with its DOM intact. If pageswap named a thumbnail before the page was stored, that name is still on the thumbnail when the page is restored. If the user then opens a different card, pageswap names a second thumbnail, and now two elements share post-image. The transition is skipped.
A small reset prevents this:
window.addEventListener('pageshow', (event) => {
if (!event.persisted) return;
document
.querySelectorAll('[data-post] img')
.forEach((img) => { img.style.viewTransitionName = ''; });
});An empty string removes the inline declaration, so the element goes back to having no name.
Styling the shared element
Once the names pair up, the browser creates a ::view-transition-group(post-image) that animates position and size from the thumbnail to the hero, with a crossfade between the two images inside it. You can tune it like any other pseudo-element:
::view-transition-group(post-image) {
animation-duration: 350ms;
animation-timing-function: ease-in-out;
}
::view-transition-old(post-image),
::view-transition-new(post-image) {
height: 100%;
object-fit: cover;
}The thumbnail and the hero often have different aspect ratios. Without object-fit: cover, the snapshots are stretched to fit the animating group and the image looks distorted mid-flight.
Common failure modes
| Symptom | Likely cause |
|---|---|
| No animation at all | Duplicate `post-image` names on one page, or the page did not opt in |
| Root animates but the image does not morph | The name was set after the capture, or the slug did not match the card |
| Image morphs on the way in but not on Back | Missing `pagereveal` handler, or `from.url` does not match your pattern |
| Image jumps at the end | The thumbnail name stayed on after the transition, or the hero loaded late |
| Works once, then fails after Back | Stale name restored from the bfcache |
If the detail hero loads slowly, the new-state snapshot may show an empty box. The render-blocking chapter covers how to hold the first render until the image's container exists.
Summary
Static names cannot represent "the card the user clicked", so a list page names one element per navigation. pageswap names the outgoing thumbnail using the destination URL. pagereveal names the incoming thumbnail using the origin URL. The detail page keeps a static name. Guard every handler against missing viewTransition, activation, or Navigation API support, escape slugs in selectors, and clean up names so only one element ever carries the shared name.
Exercise
A list page has 20 cards. A developer writes .card img { view-transition-name: post-image; } in the stylesheet, and the detail page uses the same name on its hero. Clicking a card gives a plain page load with no animation. What is wrong, and how should the list page assign the name instead?
Show answer
All 20 thumbnails share one name, and names must be unique in a page state, so the browser skips the transition. Remove the static rule from the list page. In a pageswap handler, read event.activation.entry.url, extract the slug, find the matching card's image, and set its style.viewTransitionName to post-image. Only one element then carries the name. Handle the return trip with a pagereveal handler that reads navigation.activation.from.url and names the matching thumbnail.
Exercise
Why does the pagereveal handler await event.viewTransition.finished before setting the thumbnail's name to none, and why is a pageshow handler with event.persisted also useful?
Show answer
Waiting for finished lets the animation complete before the name is removed. Removing it earlier would end the shared-element animation. Resetting it afterward stops the thumbnail from staying a named element that could collide with later names. The pageshow handler covers pages restored from the bfcache. Such a page can still carry a name set by an earlier pageswap, and clearing it avoids a duplicate when the user opens a different card.