Sub topic 2
Naming Elements with `view-transition-name`
Assume you know basic JavaScript, promises, CSS selectors, and how a single-page app updates the DOM. This chapter uses those skills to create a shared-element transition: an element appears to move smoothly from the old view to the new view.
Naming Elements with `view-transition-name`
view-transition-name gives an element a stable identity during a view transition. The browser uses that identity to match an element in the old snapshot with an element in the new snapshot.
.card-image {
view-transition-name: hero;
}The name must be unique among active transition elements in each view. If two visible elements use hero, the transition can fail or produce unexpected results. Elements without a name remain part of the root transition.
Building a Shared-Element Transition
Assign the name to the old element before starting the transition. In the update callback, remove the name from the old element and assign it to the matching element in the new view.
function openDetail(card, id) {
if (!document.startViewTransition) {
showDetail(id);
return;
}
card.style.viewTransitionName = "hero";
const transition = document.startViewTransition(() => {
card.style.viewTransitionName = "";
showDetail(id);
const image = document.querySelector(".detail-image");
image.style.viewTransitionName = "hero";
});
transition.finished.finally(() => {
const image = document.querySelector(".detail-image");
if (image) image.style.viewTransitionName = "";
});
}The browser captures the card in the old state and the detail image in the new state. It then animates the matching hero snapshots between their positions and sizes.
Keeping Names Unique, Including in Lists
A list usually contains several similar items. Give each item a name based on its unique identifier.
function nameCard(card, id) {
card.style.viewTransitionName = `card-${id}`;
}Only the element that will move should have an active name. Clear names when an element leaves the transition or when a list is rerendered.
Feature Detection and Graceful Fallback
Not every browser supports same-document view transitions. Test the API and perform the normal DOM update when it is unavailable.
function navigate(id) {
if (document.startViewTransition) {
document.startViewTransition(() => updateView(id));
} else {
updateView(id);
}
}The fallback keeps navigation functional. The transition improves presentation but should not be required for correctness.
Exercise
Why must the old and new elements use the same view-transition-name?
Show answer
The shared name tells the browser which snapshots represent the same logical element, allowing it to animate between them.