iTranslated by AI
Implementing Page Transition Animations with the View Transitions and Navigation APIs
The Navigation API has been supported since Chrome 102, and the View Transitions API has been supported since Chrome 111. In this article, I will try to implement page transition animations using these two APIs.
Demo Site & Code
In this article, I may explain things based on the following demo site and code. Please refer to them if you want to check the overall behavior or code.
View Transitions API
The View Transitions API is an API that provides a simpler method than before for animated screen transitions and DOM updates between different DOM states.
For a detailed explanation of the View Transitions API, please refer to View Transitions API - Web APIs | MDN.
Demo Page & Code
The demo page and code for the View Transitions API introduced in this article are as follows.
Capture of the View Transitions API demo screen

Animation Implementation Using the View Transitions API
Let's take a look at the code right away. The HTML structure is as follows:
<!-- Book index screen -->
<main class="main" data-transition-wrapper="book-index">
<h1 class="page-title">Book List</h1>
<div class="container">
<div class="book-index-list">
<article class="book">
<a class="book-link link" href="/view-transitions-api/?page=book-detail">
<img class="thumbnail" data-view-transition-name="thumbnail" src="..." />
<h2 class="book-title" data-view-transition-name="title">I Am a Cat</h2>
<div class="book-author">Natsume Soseki</div>
</a>
</article>
</div>
</div>
</main>
<!-- Book detail screen (initially hidden using the hidden attribute) -->
<main class="main" data-transition-wrapper="book-detail" hidden>
<h1 class="page-title">Book Details</h1>
<div class="container">
<article class="book">
<h2 class="book-title" data-view-transition-name="title">I Am a Cat</h2>
<img class="thumbnail" data-view-transition-name="thumbnail" src="..." />
<p class="book-content">I am a cat. As yet I have no name. ...</p>
<div class="book-author">Natsume Soseki</div>
</article>
<a class="link back-link" href="./">Back to List</a>
</div>
</main>
In the above example, the book index screen and the book detail screen are written within a single HTML file. Initially, the hidden attribute is added to the book detail screen to hide the element with display: none. In this case, please consider that screen transitions are being performed in a pseudo-fashion by switching the visibility of these two screens.
The following is the JavaScript code for achieving the screen transition animation.
// Executing startViewTransition
const swap = async (from, to) => {
return document.startViewTransition(() => {
from.hidden = true;
to.hidden = false;
}).updateCallbackDone;
};
const findAnchorElement = element => {
if (element.tagName === 'A') {
return element;
}
return null;
};
const findParentAnchorElement = element => {
return element.closest('a');
};
// Get screen elements
const bookIndexPage = document.querySelector(
'*[data-transition-wrapper="book-index"]'
);
const bookDetailPage = document.querySelector(
'*[data-transition-wrapper="book-detail"]'
);
const pageList = [bookIndexPage, bookDetailPage];
const documentBody = document.body;
documentBody.addEventListener('click', async e => {
const target = e.target;
// Determine if an a element (link) was clicked
const anchorElement =
findAnchorElement(target) || findParentAnchorElement(target);
// If it is an a element, perform screen transition
if (anchorElement) {
e.preventDefault();
const url = new URL(anchorElement.href);
const params = url.searchParams;
const nextPage = params.get('page') ?? 'book-index';
const nextSwapList =
nextPage === 'book-index' ? pageList : [...pageList].reverse();
await swap(...nextSwapList);
}
});
The key is the swap() function. You can see that document.startViewTransition(updateCallback) from the View Transitions API is being called within the swap() function.
// Executing document.startViewTransition
const swap = async (from, to) => {
return document.startViewTransition(() => {
// DOM update process
// Switching between the book index screen and the book detail screen
from.hidden = true;
to.hidden = false;
}).updateCallbackDone;
};
In the updateCallback of startViewTransition(updateCallback), you describe the DOM update process. In this demo, we describe the process of switching the display between the book index screen and the book detail screen.
Surprisingly, DOM updates accompanied by cross-fade animations are performed with just this simple code.
// Execute `swap()` when an a element is clicked
if (anchorElement) {
e.preventDefault();
const url = new URL(anchorElement.href);
const params = url.searchParams;
const nextPage = params.get('page') ?? 'book-index';
const nextSwapList =
nextPage === 'book-index' ? pageList : [...pageList].reverse();
await swap(...nextSwapList);
}
Now, all that's left is to execute swap() when the a element is clicked. An animated screen transition will take place between the book index screen and the book detail screen.
If you observe the behavior of the demo page here, you will notice that there are elements performing animations different from the cross-fade transition of the entire screen (the transition of the whole main element).
Specifically, the two elements performing different animations are as follows:
<!-- Book title -->
<h2 class="book-title" data-view-transition-name="title">I Am a Cat</h2>
<!-- Thumbnail -->
<img class="thumbnail" data-view-transition-name="thumbnail" src="..." />
These elements appear to move or scale (rather than cross-fade) between screen transitions. Let's check the styles applied to these elements.
*[data-view-transition-name] {
contain: paint;
}
/* View Transitions API */
*[data-view-transition-name="title"] {
view-transition-name: title;
}
*[data-view-transition-name="thumbnail"] {
view-transition-name: thumbnail;
}
There is an unfamiliar property called view-transition-name. This property is actually the reason why these two elements perform independent animations. When view-transition-name is present in both the pre-transition and post-transition states, the element with that style applied will undergo an independent screen transition.
Flow of Screen Transitions
Let's briefly confirm the flow of screen transitions using the View Transitions API.
Screen transitions with the View Transitions API proceed according to the following flow:
- The developer executes
document.startViewTransition(updateCallback). - The current screen is captured as the "old" state.
- Rendering is paused.
- The
updateCallbackis executed. - The current screen is captured as the "new" state.
- Transition pseudo-elements (a tree of pseudo-elements starting with
::view-transition) are created. - The rendering pause is lifted, and the pseudo-elements transition while animating.
- Once the transition is complete, the pseudo-elements are removed.
The View Transitions API generates visual snapshots of the state before and after the screen transition. As seen from the flow above, the screen transition animation is realized by a series of pseudo-element trees called transition pseudo-elements. If you check with Chrome DevTools, you can see that a pseudo-element tree with the following structure is generated directly under the html element during the animation:
::view-transition
├─ ::view-transition-group(root)
│ └─ ::view-transition-image-pair(root)
│ ├─ ::view-transition-old(root)
│ └─ ::view-transition-new(root)
└─ …other groups…
Transition pseudo-elements include the following:
- ::view-transition is the root pseudo-element of the screen transition tree.
-
::view-transition-group() represents a single screen transition group, generated as a child of
::view-transitionfor each screen transition name, and contains ::view-transition-image-pair(). - ::view-transition-old() is the visual snapshot of the "old" state.
- ::view-transition-new() is the visual snapshot of the "new" state.
It is possible to customize animations by writing styles for transition pseudo-elements.
@keyframes fade-in {
from { opacity: 0; }
}
@keyframes fade-out {
to { opacity: 0; }
}
@keyframes slide-from-right {
from { transform: translateX(30px); }
}
@keyframes slide-to-left {
to { transform: translateX(-30px); }
}
::view-transition-old(root) {
animation: 90ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
300ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
}
::view-transition-new(root) {
animation: 210ms cubic-bezier(0, 0, 0.2, 1) 90ms both fade-in,
300ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
}
Named View Transitions
The CSS view-transition-name property tags specific elements within the captured screen transition and tracks them individually using the specified name. Tracked elements are animated independently of the transition of the entire page.
In the demo code, view-transition-name was specified as follows:
*[data-view-transition-name="title"] {
view-transition-name: title;
}
*[data-view-transition-name="thumbnail"] {
view-transition-name: thumbnail;
}
When view-transition-name is specified, a ::view-transition-group() is created for names other than root. In the demo in this article, names title and thumbnail were assigned, so the following transition pseudo-element tree is generated:
::view-transition
├─ ::view-transition-group(root)
│ └─ ::view-transition-image-pair(root)
│ ├─ ::view-transition-old(root)
│ └─ ::view-transition-new(root)
├─ ::view-transition-group(title)
│ └─ ::view-transition-image-pair(title)
│ ├─ ::view-transition-old(title)
│ └─ ::view-transition-new(title)
└─ ::view-transition-group(thumbnail)
└─ ::view-transition-image-pair(thumbnail)
├─ ::view-transition-old(thumbnail)
└─ ::view-transition-new(thumbnail)
Animation customization is also possible for elements with a specified view-transition-name.
*[data-view-transition-name="title"] {
view-transition-name: title;
}
@keyframes fade-in {
from { opacity: 0; }
}
@keyframes fade-out {
to { opacity: 0; }
}
@keyframes slide-from-right {
from { transform: translateX(30px); }
}
@keyframes slide-to-left {
to { transform: translateX(-30px); }
}
::view-transition-old(title) {
animation: 90ms cubic-bezier(0.4, 0, 1, 1) both fade-out,
300ms cubic-bezier(0.4, 0, 0.2, 1) both slide-to-left;
}
::view-transition-new(title) {
animation: 210ms cubic-bezier(0, 0, 0.2, 1) 90ms both fade-in,
300ms cubic-bezier(0.4, 0, 0.2, 1) both slide-from-right;
}
We have now briefly reviewed the implementation of the View Transitions API demo.
In the demo so far, we described two screens in a single HTML file to simulate page transition behavior. In the next step, we will split the files so that each HTML file contains one screen. In other words, instead of toggling screen visibility using the hidden attribute, the code will be written in separate HTML files.
To do that, let's first take a look at the Navigation API.
Navigation API
The Navigation API is an API that provides the initiation, interception, and management of browser navigation actions. It also allows you to examine history entries. It is the successor to the History API and window.location.
For a detailed explanation of the Navigation API, please refer to Navigation API - Web APIs | MDN.
Demo Page & Code
The demo page and code for the Navigation API are as follows.
Capture of the Navigation API demo screen

Handling Navigation Using the Navigation API
Now, let's examine the code. To make the page transition behavior easier to understand, we have prepared two book detail screens this time.
<!-- Book index screen -->
<main class="main" data-transition-wrapper="book-index">
<h1 class="page-title">Book List</h1>
<div class="container">
<div class="book-index-list">
<article class="book">
<a class="book-link link" href="/navigation-api/detail/i-am-a-cat/">
<img class="thumbnail" data-view-transition-name="thumbnail" src="..." />
<h2 class="book-title" data-view-transition-name="title">I Am a Cat</h2>
<div class="book-author">Natsume Soseki</div>
</a>
</article>
<article class="book">
<a class="book-link link" href="/navigation-api/detail/rashomon/">
<img class="thumbnail" data-view-transition-name="thumbnail" src="..." />
<h2 class="book-title" data-view-transition-name="title">Rashomon</h2>
<div class="book-author">Akutagawa Ryunosuke</div>
</a>
</article>
</div>
</div>
</main>
<!-- Book detail screen (The Rashomon screen has the same DOM structure) -->
<main class="main" data-transition-wrapper="book-detail">
<h1 class="page-title">Book Details</h1>
<div class="container">
<article class="book">
<h2 class="book-title" data-view-transition-name="title">I Am a Cat</h2>
<img class="thumbnail" data-view-transition-name="thumbnail" src="..." />
<p class="book-content">I am a cat. As yet I have no name. ...</p>
<div class="book-author">Natsume Soseki</div>
</article>
<a class="link back-link" href="/navigation-api/">Back to List</a>
</div>
</main>
The book detail screen above is for the "I Am a Cat" page, but the "Rashomon" page has a similar DOM structure.
The JavaScript code using the Navigation API is as follows.
// HTML parsing
const parser = new DOMParser();
const parseHTML = html => {
return parser.parseFromString(html, 'text/html');
};
// Fetch HTML string using fetch
const getHTML = async url => {
return fetch(url).then(res => res.text());
};
// Swap elements
const swap = (from, to) => {
from.replaceWith(to);
};
// Events that should not be intercepted
const shouldNotIntercept = navigationEvent => {
// Reference: https://developer.chrome.com/docs/web-platform/navigation-api/#deciding-how-to-handle-a-navigation
return (
!navigationEvent.canIntercept ||
navigationEvent.hashChange ||
navigationEvent.downloadRequest ||
navigationEvent.formData
);
};
// Navigation API
navigation.addEventListener('navigate', e => {
if (shouldNotIntercept(e)) return;
const loadNextPage = async () => {
const htmlString = await getHTML(e.destination.url);
const parsedHTML = parseHTML(htmlString);
const toHTML = parsedHTML.querySelector('*[data-transition-wrapper]');
const fromHTML = document.querySelector('*[data-transition-wrapper]');
swap(fromHTML, toHTML);
document.title = parsedHTML.title;
};
// Intercept the NavigateEvent
// Describe the processing content in the handler
e.intercept({ handler: loadNextPage });
});
navigation.addEventListener('navigatesuccess', e => {
console.log(e);
});
navigation.addEventListener('navigateerror', e => {
console.error(e);
});
Among these, the following part is particularly important:
// Navigation API
navigation.addEventListener('navigate', e => {
if (shouldNotIntercept(e)) return;
const loadNextPage = async () => {
const htmlString = await getHTML(e.destination.url);
const parsedHTML = parseHTML(htmlString);
const toHTML = parsedHTML.querySelector('*[data-transition-wrapper]');
const fromHTML = document.querySelector('*[data-transition-wrapper]');
swap(fromHTML, toHTML);
document.title = parsedHTML.title;
};
// Intercept the NavigateEvent
// Describe the processing content in the handler
e.intercept({ handler: loadNextPage });
});
The Navigation API can be accessed via window.navigation. The intercept() method of NavigateEvent literally intercepts the navigation and converts it into a same-document navigation.
The handler is a callback function that defines what the navigation processing behavior should be. Here, loadNextPage() is set.
// Navigation API
// Access via `window.navigation`
navigation.addEventListener('navigate', e => {
// ...omitted
// Intercept the NavigateEvent
// Pass the processing of how to behave as a callback function to the handler
e.intercept({ handler: loadNextPage });
});
Inside loadNextPage(), the next content is fetched using fetch(), and the retrieved HTML string is converted into a DOM using DOMParser. After that, the swap() function updates the current page screen.
const loadNextPage = async () => {
// e.destination.url is the destination URL
const htmlString = await getHTML(e.destination.url);
// Convert to DOM
const parsedHTML = parseHTML(htmlString);
const toHTML = parsedHTML.querySelector('*[data-transition-wrapper]');
const fromHTML = document.querySelector('*[data-transition-wrapper]');
// Update HTML
swap(fromHTML, toHTML);
document.title = parsedHTML.title;
};
For details regarding shouldNotIntercept(), please refer to this article by Chrome Developers. You can check which navigation events should not be intercepted.
const shouldNotIntercept = navigationEvent => {
// Reference: https://developer.chrome.com/docs/web-platform/navigation-api/#deciding-how-to-handle-a-navigation
return (
!navigationEvent.canIntercept ||
navigationEvent.hashChange ||
navigationEvent.downloadRequest ||
navigationEvent.formData
);
};
If you actually observe the page behavior, it might seem (partly because no animation is implemented) that there is no difference from a normal page transition via an a element at first glance. However, if you check the Network tab in Chrome DevTools, you will see that every time a page transition occurs, the next content is being fetch()ed asynchronously.
When doing something similar with the traditional History API method, it's necessary to handle the click events of a elements and manage history using history.pushState(). With the arrival of the Navigation API, these processes can now be achieved more easily and flexibly.
Combining View Transitions API and Navigation API
Now, let's implement page transition animations by combining the View Transitions API and the Navigation API.
Demo Page & Code
The demo page and code for combining the View Transitions API and the Navigation API are as follows.
Capture of the View Transitions API and Navigation API demo screen

Implementing Page Transition Animations Using the View Transitions API and Navigation API
In this demo, the main focus is combining the View Transitions API and Navigation API that have appeared so far, so there isn't much particularly new to discuss. Especially regarding the code, there are almost no changes, so only the parts that have changed will be excerpted and described.
<!-- Book list screen -->
<article class="book">
<a class="book-link link" href="/async-transition-animation/detail/i-am-a-cat/"
>
<img
class="thumbnail" data-view-transition-name="thumbnail" style="--view-transition-name: thumbnail-1" src="..."
/>
<h2 class="book-title" data-view-transition-name="title" style="--view-transition-name: title-1"
>I Am a Cat</h2>
<div class="book-author">Natsume Soseki</div>
</a>
</article>
<article class="book">
<a class="book-link link" href="/async-transition-animation/detail/rashomon/">
<img class="thumbnail" data-view-transition-name="thumbnail" style="--view-transition-name: thumbnail-2" src="..." />
<h2 class="book-title" data-view-transition-name="title" style="--view-transition-name: title-2">Rashomon</h2>
<div class="book-author">Akutagawa Ryunosuke</div>
</a>
</article>
<!-- Book detail screen -->
<article class="book">
<h2 class="book-title" data-view-transition-name="title" style="--view-transition-name: title-1"
>I Am a Cat</h2>
<img class="thumbnail" data-view-transition-name="thumbnail" style="--view-transition-name: thumbnail-1" src="..." />
<p class="book-content"> I am a cat. As yet I have no name. ... </p>
<div class="book-author">Natsume Soseki</div>
</article>
/* View Transitions API */
*[data-view-transition-name] {
view-transition-name: var(--view-transition-name);
contain: paint;
}
/* Animation duration adjustment */
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation-duration: 1s;
}
Care is needed regarding view-transition-name. The value of view-transition-name must be unique for each screen. In other words, on the list screen, it is necessary to change the view-transition-name for each title and each thumbnail. In this case, we use CSS variables (--view-transition-name) to assign a unique name to each element.
// View Transitions API
const swap = (from, to) => {
return document.startViewTransition(() => {
from.replaceWith(to);
}).updateCallbackDone;
};
There are almost no changes to the JavaScript from the Navigation API demo, but the contents of swap() are processed within document.startViewTransition().
That concludes the explanation of the page transition animation demo using the View Transitions API and Navigation API. When you actually check the behavior of the page transitions, you should be able to see that screen transitions are being performed asynchronously with animation.
Cross Document View Transitions
Next, I'll touch upon Cross Document View Transitions, which is an even more advanced topic.
Demo Page & Code
The demo page and code for Cross Document View Transitions are as follows:
Capture of the Cross Document View Transitions demo screen

Page Transition Animation in MPA
The View Transitions API we have discussed so far was mainly for same-document, SPA (Single-page application) use. In other words, it could not be used in MPA (Multi-Page Application), and if you wanted to perform screen transitions between pages, you had to fetch the contents of the next page asynchronously using fetch().
On the other hand, support for the View Transitions API between different pages (documents) is also being considered. At this time, you need to declare a meta tag as follows:
<meta name="view-transition" content="same-origin" />
In fact, if you just want to perform transitions with simple animations, you don't even need to write any JavaScript (no fetch() is necessary).
If you want to check the behavior, as mentioned before, please set chrome://flags/#view-transition-on-navigation to Enabled and access the demo page. Even though this demo page does not perform any fetch() processing, page transitions are occurring with animations.
This is actually realized with MPA behavior, and if you check the Network tab in Chrome DevTools, you can confirm that page transitions are happening synchronously.
Conclusion
In this article, I introduced how to implement page transition animations using the View Transitions API and Navigation API.
When I first read about Cross Document View Transitions, I was shocked that even writing JavaScript would become unnecessary. Considering other browsers, it might take a little more time before it is widely supported, but I want to continue catching up with it.
References
Discussion