Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/vtbag/website. The @vtbag website. ⭐️ Please star to support this work! ⭐️
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259---title: View Transition JavaScript APIdescription: How to interact with view transitions using JavaScripthead: - tag: meta attrs: property: "og:image" content: "/javascript-og.png"---
Browser-native cross-document view transitions can be [created entirely with CSS](#cross-document-view-transitions), without the need for JavaScript. However, even for cross-document view transitions, JavaScript becomes essential for advanced functionality:
- Triggering same-page view transitions with `startViewTransition()`- Dynamically modifying CSS properties like `view-transition-name`- Defining view transition types- Executing code at the start or end of a transition
## Same-Document View Transitions
Same-document view transitions are amazing! You assign view transition names to the HTML elements you want to animate during the transition. The transition spans from the current DOM state to a future version, which is generated by calling and awaiting an update function.
### startViewTransition()
You start a same-document view transition with an update callback that transforms the current DOM to the future state. The View Transition API takes care of creating pseudo-elements and running animations that smoothly transition from the old state to the new one.
When you call `startViewTransition()`, it is good practice to care for users that do not want motion effects and for browsers that do not support the API:
```jsif ( window.matchMedia("(prefers-reduced-motion: reduce)") || !document.startViewTransition) { updateCallback();} else { document.startViewTransition(updateCallback);}```
For users who prefer reduced motion or when the browser doesn't support the View Transition API, the code above directly executes the update function without calling `startViewTransition()`.
:::noteCalling `startViewTransition()` while another view transition is active will end the active view transition in the same way as [`skipTransition()`](#skiptransition) ends the view transition: any running animation abruptly jumps to the end before the new transition starts. :::
:::cautionNo rule without an [exception](https://drafts.csswg.org/css-view-transitions-2/#Element-ViewTransition-prepare): If you start a same-document view transition while a cross-document view transition is active, the new transition will be skipped, not the active one. :::
The update callback can either be a synchronous or asynchronous function. If it's asynchronous, the View Transition API will wait for it to settle. However, you should aim to spend as little time as possible inside the callback. For one thing, the browser freezes the renderer while the update callback executes. And browsers may impose time limits. For Chrome this seems to be 4 seconds before it loses its temper. If you need an expensive preparation for the transition, like loading and parsing a new DOM from file, you better do that before you call `startViewTransition()`. The update callback is optional, so you can even transition to the same version of the DOM by omitting the update function, which might make sense with custom animations.
You can also pass an options object to `startViewTransition()` to define [view transition types](/basics/styling/#with-types) that should be active during the transition.
```jsdocument.startViewTransition({ types: ["boom", "backward"], update: changeTheDOM,});```
Here is the full signature for `startViewTransition`
```tstype UpdateCallback = undefined | (() => void | Promise<void>);type StartViewTransitionOptions = { types?: string[] | Set<string>; update?: UpdateCallback;};
interface Document { startViewTransition( param?: StartViewTransitionOptions | UpdateCallback ): ViewTransition;}```
### ViewTransition Object
The `startViewTransition()` function returns an object that includes promises, the current transition types, the root/scope of a scoped view transition, and a function to skip the animations.
```tsinterface ViewTransition { readonly updateCallbackDone: Promise<undefined>; readonly ready: Promise<undefined>; readonly finished: Promise<undefined>; readonly types?: Set<string>; readonly transitionRoot?: Element; skipTransition(): void; waitUntil(Promise<any> promise): void;}```
#### Promises
The promises allow you to hook into the different stages of the view transition process.
- The `updateCallbackDone` promise resolves once the update callback fulfils. You can use this to (synchronously) make last-minute changes before the new images are created. If the update function rejects, the `updateCallbackDone` promise rejects, too. View transition processing ends, and the `ready` and `finished` promises also reject.
- The `ready` promise settles once the pseudo-elements have been inserted into the DOM. Inserting the pseudo-elements triggers their animations. For example, you can use this promise to add your own JavaScript animations using the Web Animation API or to interact with the browser defined default animations, see [below](#manipulating-animations).
:::caution If there are errors, like duplicate view transition names, the `ready` promise will reject. And if that happens during the capturing of the old images, it will reject before `updateCallbackDone` settles. :::
- Lastly, the `finished` promise settles once all [waited for promises](#waituntil) and all animations on view transition pseudo-elements are complete and the pseudo-elements have been removed. It resolves with the same outcome as `updateCallbackDone`.
When using the promises, your call to `startViewTransition()` might look something like this:
```jsif (document.startViewTransition && window.matchMedia('(prefers-reduced-motion: no-preference)')) { const viewTransition = document.startViewTransition({update: updateCallback, types: ...}); viewTransition.updateCallbackDone.catch(err => ... error handling ...); viewTransition.ready.catch(err => ... error handling ...); viewTransition.ready.then(() => ... trigger parallel animation ...); viewTransition.finished.finally(() => ... clean up ...)} else { updateCallback();}```You might also see examples using the `async/await` syntax like this:```jsconst transition = document.startViewTransition(...);await transition.ready;// tweak the animations or start your own...```While this might feel more readable, it is not always a good choice. If you want to handle possible errors, you need try/catch blocks around each await.
#### Manipulating Animations
To manipulate the browser defined default animations, you can use the `document.getAnimations()` function to get a list of all animations currently running on the page. You can then filter this list for animations that are running on view transition pseudo-elements and manipulate them as you like. For example, you can pause them, change their playback rate, or even reverse them.
For element-scoped view transitions, you can also call `element.getAnimations({subtree: true})` on the transition root element to get only the animations that are running inside that subtree.
Here is an example that pauses all view transition animations (of a global view transition) at the start of the transition:
```ts title="Pausing all view transition animations"const transition = document.startViewTransition(...);transition.ready.then(() => { document.getAnimations() .filter((a) => a.effect?.pseudoElement?.startsWith("::view-transition")) .forEach((a) => {a.pause(); a.currentTime = 0});});```This might come in handy if you want the animations to pause until some resource is available, e.g., an image is loaded. `a.play()` then ends the pause. But for smooth animations, it would be better to delay the start of the view transition instead.
Once you paused the animations, you can move freely within the timeline by setting the `currentTime` property of the animation to a number between 0 and the animation's total duration in milliseconds. You can also use the `playbackRate` property to speed up or slow down the animations. You can reverse the animation by setting `playbackRate` to a negative value.
#### skipTransition()
Calling `skipTransition()` stops the current view transition animations or prevents their start if the `ready` promise hasn't settled yet.
If called before or during the update callback, it doesn't affect the update itself, nor does it impact the processing or the outcome of the updateCallbackDone promise.
Skipping the transition means that the pseudo-element tree created by the view transition API is removed (or never inserted). Without the pseudo-elements, the browser directly shows the new DOM state. Therefore, a skipped view transition looks like the animation would jump abruptly to its end state.
#### Types
You can dynamically add or remove view transition types during the view transition by modifying the `types` object. Such changes will directly affect CSS rules that use the `:active-view-transition-type` pseudo-class.
View transition types are a feature of Level 2 of the View Transition API. They [can be polyfilled](/tools/utensil-drawer/#the-postcss-active-view-transition-type-postcss-plugin) if you want to use them with Level 1 implementations.
#### transitionRoot
For scoped view transitions, this property returns the element on which `Element.startViewTransition` was called. For view transitions started on the `document`, either same-document or cross-document, it should return `document.documentElement` but does return `null` on current implementations. This property is only implemented in browsers that support scoped view transitions.
#### waitUntil
The `finished` promise of a view transition does only settle once all animations on pseudo-elements have come to an end. With `waitUntil()` you can pass a promise to the view transition to wait for.
When you call it multiple times, the view transition will remember all the passed promises.
The `finished` promise will then wait until all animations of the view transition pseudo-elements ended and until all passed promises have settled.
### Checking for an Active View Transition
The View Transition API now offers a way to check whether some view transition is currently active or not. If so, the `document.activeViewTransition()` function returns the ViewTransition object of a currently active view transition. This works for same-document and cross-document view transitions alike, but does not yet seem to work for scoped view transitions when calling `Element.activeViewTransition()`.
If you use [`mayStartViewTransition`](/tools/utensil-drawer/#maystartviewtransition) from the Utensil Drawer, you can access the current `ViewTransition` object by calling [getCurrentViewTransition](/tools/utensil-drawer/#current-view-transition).
### Cancelling and Chaining
Calling `startViewTransition()` while another view transition is active will interrupt the current view transition, fast forward to the end state of the animations, and start the new view transition from there.
If you want to avoid these jerky jumps, you can either
- chain the update callback functions, passing the chained callback to a single call of `startViewTransition()`, or- chain multiple calls to `startViewTransition()` by awaiting the `finished` promise before starting the next view transition.
The [`mayStartViewTransition()`](/tools/utensil-drawer/#maystartviewtransition) function from the Utensil Drawer has automatic support for both strategies.
### Scoped View Transitions
[Scoped view transitions](https://github.com/WICG/view-transitions/blob/main/scoped-transitions.md) are rooted at arbitrary DOM elements. Instead of calling ```jsdocument.startViewTransition()``` it's ```jselement.startViewTransition()``` This has some severe advantages:
- Rendering is only blocked on the DOM subtree rooted at element. The rest of the page is still interactive.- There can be several scoped view transitions on the page and they can independently perform in parallel.
Scoped view transitions are not widely supported yet. If your [browser supports](/basics/test-page/) them, this site features a [small example on clipping](/basics/hide-and-seek/#clipping-with-scoped-view-transition-groups).
#### view-transition-scope
[`view-transition-scope`](https://drafts.csswg.org/css-view-transitions-2/#view-transition-scope-prop) is a relatively new CSS property currently supported only in Chrome.
It defines a visibility boundary for view transition names. The only valid values for `view-transition-scope` are `all` and `none`.
When it is set to `all` on an element, all view transition names defined within that element's DOM subtree are hidden from view transitions rooted outside that subtree.
The API automatically inserts `view-transition-scope: all` at the transition root of an active view transition, and the property exists only while that view transition is active. The transition root is either the document root or the element on which `element.startViewTransition()` was called.
Without additional precautions, elements can effectively be claimed by the first view transition that encounters them. This can lead to accidental coupling between unrelated transitions that happen to reference the same elements. To avoid this, it can be better to define these boundaries explicitly. By setting `view-transition-scope: all` ahead of time on elements that may act as view transition roots, you can clearly assign which elements belong to which transition and prevent unintended interactions between concurrent or overlapping view transitions.
## Cross-Document View Transitions
You activate cross-document view transitions by adding the following incantation to the styles of all pages that should participate in view transitions:
```css@view-transition { navigation: auto;}```
Opting in to cross-document view transitions is CSS-only. But cross-document view transitions, too, have their JavaScript API.
Cross-document view transitions work similarly to [same-document](#same-document-view-transitions) ones but are triggered by navigation. In particular you can get access to the [view transition object](#viewtransition-object) in event listeners for the new `pageswap` and `pagereveal` events.
### Pageswap and Pagereveal Events
Two key events enable JavaScript interaction: `pageswap`, dispatched just before leaving the old page, and `pagereveal`, dispatched before the new page renders.
### ViewTransition Object
Both events include a `viewTransition` property, which holds a `ViewTransition` object if the transition is part of a cross-document view transition. The object has the [same structure](/basics/javascript/#viewtransition-object) as for same-document view transitions.
For `pageswap`, if `viewTransition` is defined, its promises will never settle because the page is unloaded before it is "updated".For `pagereveal`, if `viewTransition` is defined, its `updateCallbackDone` promise is immediately settled.
The events allow you to manipulate the DOM or CSS properties right before snapshots are taken or the new page's live elements are captured. In particular, they allow for [setting view transition types](/basics/styling/#with-types) for the current view transition.
In a `pageswap` listener, you can define view transition types by adding them to `event.viewTransition.types`, which are then only applied to the old page. The types can be used to [control via CSS](/tools/turn-signal/#switching-transition-names) what view transition names are defined on the old page. You can also directly modify view transition names in the listener as snapshots for the `::view-transition-old` pseudo elements are taken after this event is dispatched.
Similarly, `pagereveal` listeners allow you to tweak view transition names and types for the new page. Again, live elements for the `::view-transition-new` pseudo-elements are being captured after the event.
### Activation Object
The `pageswap` event also provides a [`NavigationActivation`](https://developer.mozilla.org/en-US/docs/Web/API/NavigationActivation) object via its `activation` property, offering details about the current page (`from`) and next page (`entry`). While the `pagereveal` event does not include this property, you can use `navigation.activation` to access information about the previous page (`from`) and current page (`entry`). Use with some caution: the Navigation API only became baseline in late 2025.