Sub topic 8
Keeping names unique, including in lists
This chapter assumes you know how view-transition-name marks an element for its own snapshot, and how document.startViewTransition() captures an old and a new state. Here you will learn the rule that keeps those names working and how to apply it to repeated elements such as list items.
The uniqueness rule
A view transition pairs elements across the old and new states by name. An old element named card-3 animates into the new element named card-3. For that pairing to be unambiguous, each name may appear on only one rendered element per state.
- In the old state, no two elements may share a name.
- In the new state, no two elements may share a name.
- The same name may appear once in each state. That is how a shared-element transition works.
- Elements that are not rendered, such as those with
display: none, do not count.
The browser checks the rule when it captures each state. If it finds a duplicate, it abandons the transition. The DOM update still happens, but nothing animates.
What a duplicate looks like
Consider a card list where every card is given the same name by a careless CSS rule.
.card {
view-transition-name: card;
}Every .card now has the name card. Chromium logs a console error that mentions a duplicate view-transition-name, and the transition is skipped. You can observe this from JavaScript.
const transition = document.startViewTransition(() => updateView());
transition.ready.catch((error) => {
console.warn('Transition skipped:', error.name, error.message);
});
await transition.updateCallbackDone;When a transition is skipped, ready rejects with an InvalidStateError. updateCallbackDone still resolves, because the update callback runs either way. Treat a rejected ready as "no animation happened", not as "the update failed". Do not put required logic after await transition.ready without handling the rejection.
Naming list items dynamically
A static stylesheet cannot give each item of a data-driven list its own name. The usual solution is to set the name from JavaScript, using the item's stable identifier.
const list = document.querySelector('#todo-list');
let items = [
{ id: 1, text: 'Write draft' },
{ id: 2, text: 'Review notes' },
{ id: 3, text: 'Publish' }
];
function nameFor(id) {
return `item-${String(id).replace(/[^a-zA-Z0-9_-]/g, '-')}`;
}
function render() {
list.replaceChildren(
...items.map((item) => {
const li = document.createElement('li');
li.textContent = item.text;
li.style.viewTransitionName = nameFor(item.id);
return li;
})
);
}
function shuffle() {
const update = () => {
items = [...items].sort(() => Math.random() - 0.5);
render();
};
if (!document.startViewTransition) {
update();
return;
}
document.startViewTransition(update);
}
render();Each item keeps the same name across renders, so after a shuffle the browser animates every item from its old position to its new one. The key decision is to derive the name from the data identity (item.id), not from the position. A name based on the index would pair the wrong elements as soon as the order changed.
Why the helper sanitizes the id
The name must be a valid CSS <custom-ident>. Setting an invalid value through style.viewTransitionName is ignored without any error, so the element simply has no name and does not animate. The nameFor helper avoids three problems:
- Names that start with a digit are invalid, so the helper adds the
item-prefix. - Spaces and punctuation are invalid, so the helper replaces them with hyphens.
- The keyword
nonemeans "no name", androotbelongs to the document element, so a prefix keeps your names clear of both.
Sanitizing can create collisions. The ids a b and a-b both become item-a-b. If your ids can contain such characters, use a numeric or generated id for the name instead of cleaning arbitrary text.
| Name source | Stable across reorders | Safe characters | Risk |
|---|---|---|---|
| Array index | No | Yes | Wrong pairing after a reorder |
| Database id (number) | Yes | Yes, with a prefix | Digit-first names need a prefix |
| Slug or title text | Yes | Not always | Invalid characters and collisions |
| `crypto.randomUUID()` stored on the item | Yes | Needs a prefix | Must be stored, not regenerated per render |
Naming only what needs to move
Every named element gets its own snapshot and its own pseudo-element group, which costs memory and rendering time. Naming all rows of a list of thousands is wasteful, and most are off screen anyway. Two common strategies reduce the cost:
- Name only the items currently in the viewport.
- Name only the element involved in the interaction, as in the hero example from the shared-element chapter, and remove the name afterwards.
The second strategy also guarantees uniqueness, because at most one element holds the name at any moment.
function openFromList(card, id) {
const name = `card-${id}`;
const apply = () => showDetail(id);
if (!document.startViewTransition) {
apply();
return;
}
card.style.viewTransitionName = name;
const transition = document.startViewTransition(() => {
card.style.viewTransitionName = '';
apply();
document.querySelector('.detail-image').style.viewTransitionName = name;
});
transition.finished.finally(() => {
const detail = document.querySelector('.detail-image');
if (detail) detail.style.viewTransitionName = '';
});
}The name is removed from the card inside the callback, before the new state is captured. If both the card and the detail image still carried card-7 in the new state, you would have a duplicate and the transition would be skipped. This is the most frequent cause of duplicates in shared-element code.
Names and CSS selectors
The name you assign is also the argument in the pseudo-element selectors. A dynamic name such as item-3 is targeted with ::view-transition-group(item-3). You cannot write a rule for every possible id ahead of time. Two approaches work:
- Use the wildcard
*to style all groups at once, for example::view-transition-group(*). - Use
view-transition-classto give many differently named elements a shared label. The class is covered in a later chapter.
Finding duplicates
When a transition is skipped and you suspect duplicates, run this helper in the console. It lists every rendered element whose computed name is shared.
function findDuplicateNames() {
const seen = new Map();
for (const el of document.querySelectorAll('*')) {
const name = getComputedStyle(el).viewTransitionName;
if (name && name !== 'none') {
seen.set(name, [...(seen.get(name) ?? []), el]);
}
}
return [...seen].filter(([, elements]) => elements.length > 1);
}
console.table(findDuplicateNames().map(([name, els]) => ({ name, count: els.length })));Run it at both moments that matter: just before calling startViewTransition(), and inside the update callback after the DOM change. The first checks the old state and the second checks the new one.
Summary of rules
- One name per rendered element per state.
- Derive names from stable data identity, not from position.
- Use valid identifiers, with a prefix.
- Remove names that should not appear in the new state.
- Name only what needs to animate.
Exercise
A list renders each row with li.style.viewTransitionName = 'row-' + index. After the user deletes the first row and the update runs in startViewTransition(), the remaining rows animate to the wrong places. Why does this happen, and how do you fix it?
Show answer
The name is based on the index, so after the deletion the row that was at index 1 now has index 0 and takes the name row-0. The browser pairs it with the old deleted row instead of its own previous snapshot. The fix is to base the name on a stable identifier, for example 'row-' + item.id, so each row keeps the same name before and after the update.
Exercise
You open a detail view from a card. The card has view-transition-name: hero in the old state, and the detail image also has hero in the new state, but nothing animates and the console reports a duplicate name. What is the most likely cause?
Show answer
The card still has the name hero when the new state is captured, so two rendered elements share it in the new state. Clear the card's name inside the update callback, before the new state is captured, and assign hero only to the detail image.