files/en-us/web/api/document/startviewtransition/index.md
{{APIRef("View Transition API")}}
The startViewTransition() method of the {{domxref("Document")}} interface starts a new same-document (SPA) view transition and returns a {{domxref("ViewTransition")}} object to represent it.
When startViewTransition() is invoked, a sequence of steps is followed as explained in The view transition process.
startViewTransition()
startViewTransition(updateCallback)
startViewTransition(options)
updateCallback {{optional_inline}}
options {{optional_inline}}
update {{optional_inline}}
updateCallback function described above. Defaults to null.types {{optional_inline}}
A {{domxref("ViewTransition")}} object instance.
See View transition API > Examples for a list of full examples.
In this same-document view transition, we check if the browser supports view transitions.
If there's no support, we set the background color using a fallback method which is applied immediately.
Otherwise, we can safely call document.startViewTransition() with animation rules that we define in CSS.
<main>
<section></section>
<button id="change-color">Change color</button>
</main>
We are setting the animation-duration to 2 seconds using the {{CSSXRef("::view-transition-group")}} pseudo-element.
html {
--bg: indigo;
}
main {
display: flex;
flex-direction: column;
gap: 5px;
}
section {
background-color: var(--bg);
height: 60px;
border-radius: 5px;
}
::view-transition-group(root) {
animation-duration: 2s;
}
const colors = ["darkred", "darkslateblue", "darkgreen"];
const colBlock = document.querySelector("section");
let count = 0;
const updateColor = () => {
colBlock.style = `--bg: ${colors[count]}`;
count = count !== colors.length - 1 ? ++count : 0;
};
const changeColor = () => {
// Fallback for browsers that don't support View Transitions:
if (!document.startViewTransition) {
updateColor();
return;
}
// With View Transitions:
const transition = document.startViewTransition(() => {
updateColor();
});
};
const changeColorButton = document.querySelector("#change-color");
changeColorButton.addEventListener("click", changeColor);
changeColorButton.addEventListener("keypress", changeColor);
If view transitions are supported, clicking the button will transition the color from one to another over 2 seconds. Otherwise, the background color is set using a fallback method, without any animation.
{{EmbedLiveSample('color_change', '100%', '120')}}
{{Specifications}}
{{Compat}}