Skip to content

176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.

feat: move View Transitions API to the guided-steps page

matin83f641363768
diff --git a/animations/03-page-transitions/view-transitions-api/README.md b/animations/03-page-transitions/view-transitions-api/README.md
index 33d97d85..8507ca5e 100644
--- a/animations/03-page-transitions/view-transitions-api/README.md
+++ b/animations/03-page-transitions/view-transitions-api/README.md
@@ -1,7 +1,7 @@
# View Transitions API
## What it is
-The View Transitions API is a browser feature that animates between two DOM states without you having to coordinate the old and new elements by hand. You call `document.startViewTransition()` and pass a callback that mutates the DOM; the browser snapshots the page before and after, then cross-fades or otherwise animates between the two snapshots. The choreography is customized entirely through CSS pseudo-elements, so the same JavaScript can drive a fade, a slide, or a zoom.
+The View Transitions API is a browser feature that animates a change of page for you. You tell the browser when the page is about to change; it takes a picture of the page before and after, then animates from one picture to the other. CSS decides how the pictures move, so the same click can fade, slide, zoom or tilt.
## When to use it
- Same-document navigation in SPAs where you swap page content in place
@@ -15,14 +15,16 @@ Wrap the DOM mutation in `startViewTransition()`. The browser captures the curre
```js
async function navigate(next){
if(next===current||animating)return;
- const prev=current;current=next;
+ animating=true;current=next;
document.documentElement.dataset.vt = style==='crossfade' ? '' : style;
+ document.documentElement.style.setProperty('--vt-dur', dur+'ms');
if(supportsVT){
- const t = document.startViewTransition(()=>switchPage(prev,next));
+ const t = document.startViewTransition(()=>showPage(current));
await t.finished;
}else{
/* manual opacity fallback */
}
+ animating=false;
}
```
@@ -36,25 +38,24 @@ async function navigate(next){
@keyframes vt-in { from{opacity:0} to{opacity:1} }
```
-Switching the `data-vt` attribute swaps in a different keyframe set (slide, zoom, or a rotate-based custom style), so one code path produces four distinct transitions. `t.finished` resolves when the animation completes, which the demo awaits to gate re-entry.
+Switching the `data-vt` attribute swaps in a different keyframe set (slide, zoom, or a slight tilt), so one code path produces four distinct transitions, and Speed and Feel set the `--vt-dur` and `--vt-ease` custom properties the keyframes read. `t.finished` resolves when the animation completes, which the demo awaits to gate re-entry. The update callback shows the resting state for the current page as it is when the callback runs, so a transition that is skipped (by Reset, or by pressing Show me again) cannot bring back an older page.
## Key parameters
| Parameter | Default | Effect |
|-----------|---------|--------|
-| `--vt-dur` | 500ms | Snapshot animation length; under ~150ms reads as an instant swap |
-| `--vt-ease` | ease-in-out | Timing curve applied to both old and new pseudo-elements |
-| `view-transition-name` | `page-content` | Names the tracked region; each name animates as its own snapshot pair |
-| Transition style | crossfade | Selects the keyframe set (crossfade / slide / zoom / custom rotate) |
+| Transition style | Fade | Fade blends the two pictures; Slide pushes the old one out to the left as the new one comes in from the right; Zoom shrinks the old one away as the new one settles from slightly larger; Tilt turns both slightly as they fade |
+| Speed | Normal | How long the change takes: slow is 800ms, normal 500ms and fast 300ms; under about 150ms it reads as an instant swap |
+| Feel | Gentle | Gentle eases in and out; Smooth slows to a stop; Even keeps one steady pace |
## Production notes
-- **Feature-detect** with `'startViewTransition' in document` and fall back to a manual opacity cross-fade — the demo does exactly this so unsupported browsers still transition.
+- **Feature-detect** with `'startViewTransition' in document` and fall back to a manual opacity cross-fade — the demo does exactly this, so browsers without the API still get a simple 300ms fade, whatever the Transition style and Speed.
- **Suppress the root animation** (`::view-transition-old(root)`) when you only want a sub-region to animate; otherwise the whole page cross-fades underneath your named region.
- **Every `view-transition-name` must be unique** on the page at capture time. Two elements sharing a name in the same snapshot throws and aborts the transition.
-- **Honor reduced motion** — the demo drops straight to `switchPage()` with no animation when `prefers-reduced-motion: reduce` is set.
+- **Honor reduced motion** — the demo drops straight to `showPage()` with no animation when `prefers-reduced-motion: reduce` is set.
- **Library equivalents**: Astro's `<ViewTransitions />` and Next.js's experimental view-transition support wrap this API for cross-document navigation. Barba.js and Swup predate it and polyfill the same idea with manual snapshotting; on supported browsers you often no longer need them.
## See also
-- [Crossfade](../crossfade/) — the default View Transitions style, built manually for comparison
-- [Slide Transition](../slide-transition/) — the slide keyframe set as a standalone technique
-- [Zoom Transition](../zoom-transition/) — the zoom keyframe set as a standalone technique
-- [Shared Element Transition](../shared-element-transition/) — continuity for a single element rather than the whole page
+- [Crossfade Transition](../crossfade/) — the same fade, built by hand
+- [Slide Transition](../slide-transition/) — pages slide, with a sense of direction
+- [Zoom Transition](../zoom-transition/) — three ways to zoom between pages
+- [Shared Element Transition](../shared-element-transition/) — one picture grows into the next page
diff --git a/animations/03-page-transitions/view-transitions-api/index.html b/animations/03-page-transitions/view-transitions-api/index.html
index 4632d08c..a300980d 100644
--- a/animations/03-page-transitions/view-transitions-api/index.html
+++ b/animations/03-page-transitions/view-transitions-api/index.html
@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View Transitions API — Animation Handbook</title>
- <meta name="description" content="document.startViewTransition() — the browser captures before/after and animates automatically.">
+ <meta name="description" content="The browser animates the change between two pages for you. Best for web apps.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/03-page-transitions/view-transitions-api/">
<link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
<link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
@@ -12,37 +12,34 @@
<meta property="og:type" content="article">
<meta property="og:site_name" content="Animation Handbook">
<meta property="og:title" content="View Transitions API — Animation Handbook">
- <meta property="og:description" content="document.startViewTransition() — the browser captures before/after and animates automatically.">
+ <meta property="og:description" content="The browser animates the change between two pages for you. Best for web apps.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/03-page-transitions/view-transitions-api/">
<meta property="og:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="View Transitions API — Animation Handbook">
- <meta name="twitter:description" content="document.startViewTransition() — the browser captures before/after and animates automatically.">
+ <meta name="twitter:description" content="The browser animates the change between two pages for you. Best for web apps.">
<meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
- <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "View Transitions API", "name": "View Transitions API", "description": "document.startViewTransition() — the browser captures before/after and animates automatically.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/03-page-transitions/view-transitions-api/", "inLanguage": "en", "articleSection": "Page Transitions", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Page Transitions, View Transitions API"}</script>
+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "View Transitions API", "name": "View Transitions API", "description": "The browser animates the change between two pages for you. Best for web apps.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/03-page-transitions/view-transitions-api/", "inLanguage": "en", "articleSection": "Page Transitions", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Page Transitions, View Transitions API"}</script>
<style>
- @font-face{font-family:'Bricolage';src:url('../../../assets/fonts/brico-700.woff2') format('woff2');font-weight:700;font-display:swap}
- @font-face{font-family:'Bricolage';src:url('../../../assets/fonts/brico-800.woff2') format('woff2');font-weight:800;font-display:swap}
- @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}
- @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-500.woff2') format('woff2');font-weight:500;font-display:swap}
- :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#b98cff;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px;--vt-dur:0.5s;--vt-ease:ease-in-out}
+ :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#b98cff;--ui-text:#f4f4f2;--ui-muted:#8a8a92;--vt-dur:0.5s;--vt-ease:ease-in-out}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
- body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}
- header{margin-bottom:20px}
- header h1{font-family:var(--disp);font-weight:700;font-size:clamp(11px,1.8vw,15px);letter-spacing:-.01em}
- header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}
- .layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}
- .stage{flex:1;min-width:0;height:var(--stage-h);border:1px solid var(--ui-border);border-radius:8px;background:var(--bg);overflow:hidden;display:flex;flex-direction:column}
+ .stage{display:flex;flex-direction:column;overflow:hidden;background:var(--bg);color:var(--ui-text)}
.mini-nav{display:flex;gap:6px;padding:10px 12px;background:var(--ui-bg);border-bottom:1px solid var(--ui-border);flex-shrink:0}
- .nav-btn{background:none;border:1px solid var(--ui-border);color:var(--ui-muted);font-family:var(--mono);font-size:10px;padding:6px 14px;border-radius:4px;cursor:pointer;min-height:44px}
+ .nav-btn{background:none;border:1px solid var(--ui-border);color:var(--ui-muted);font:inherit;font-size:13px;padding:0 12px;border-radius:4px;cursor:pointer;min-height:44px}
.nav-btn.active{border-color:var(--ui-accent);color:var(--ui-accent)}
.page-area{flex:1;position:relative;overflow:hidden;view-transition-name:page-content}
.page{position:absolute;inset:0;pointer-events:none}
.page.active{pointer-events:auto}
/* Suppress root animation — we only want page-content to animate */
::view-transition-old(root),::view-transition-new(root){animation:none}
- /* Keep the sliding/scaling snapshots inside the stage instead of bleeding over the page */
- ::view-transition-group(page-content){overflow:clip}
+ /* The browser draws the pictures above the whole page, so the stage cannot clip them: keep the sliding and scaling
+ pictures inside the page area, with the stage's rounded bottom corners (its 12px radius inside its 1px border) */
+ ::view-transition-group(page-content){overflow:clip;border-radius:0 0 11px 11px}
+ /* The site's top bar stays drawn above the transition, exactly as it looks at rest: both its pictures stay still and
+ only the new one shows (with both, its slightly see-through background would turn more solid during a transition) */
+ .hb-bar{view-transition-name:hb-bar}
+ ::view-transition-group(hb-bar),::view-transition-old(hb-bar),::view-transition-new(hb-bar){animation:none}
+ ::view-transition-old(hb-bar){opacity:0}
/* Default: crossfade */
::view-transition-old(page-content){animation:vt-out var(--vt-dur) var(--vt-ease) both}
::view-transition-new(page-content){animation:vt-in var(--vt-dur) var(--vt-ease) both}
@@ -58,155 +55,255 @@
[data-vt="zoom"]::view-transition-new(page-content){animation:vt-zoom-in var(--vt-dur) var(--vt-ease) both}
@keyframes vt-zoom-out{to{opacity:0;transform:scale(0.8)}}
@keyframes vt-zoom-in{from{opacity:0;transform:scale(1.15)}}
- /* Custom style */
+ /* Tilt style */
[data-vt="custom"]::view-transition-old(page-content){animation:vt-custom-out var(--vt-dur) var(--vt-ease) both}
[data-vt="custom"]::view-transition-new(page-content){animation:vt-custom-in var(--vt-dur) var(--vt-ease) both}
@keyframes vt-custom-out{to{opacity:0;transform:scale(0.9) rotate(-2deg)}}
@keyframes vt-custom-in{from{opacity:0;transform:scale(0.9) rotate(2deg)}}
.pc{display:flex;flex-direction:column;justify-content:center;height:100%;padding:clamp(20px,4vw,40px);gap:12px}
- .pe{font-size:10px;text-transform:uppercase;letter-spacing:3px;opacity:.4}
+ .pe{font-size:10px;text-transform:uppercase;letter-spacing:3px;opacity:.6}
.ph{font-size:clamp(22px,3.5vw,36px);font-weight:bold;line-height:1.15}
.pp{font-size:12px;opacity:.6;line-height:1.65;max-width:320px}
.pgrid{display:grid;grid-template-columns:repeat(3,1fr);gap:6px;margin-top:4px}
.gi{background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.1);border-radius:6px;padding:18px 12px;font-size:11px}
.pstat{display:flex;gap:20px;margin-top:4px}
.pstat b{display:block;font-size:clamp(18px,2.5vw,24px);color:#58a6ff}
- .pstat span{font-size:9px;opacity:.4;text-transform:uppercase;letter-spacing:1px}
- .support-banner{font-size:10px;padding:6px 10px;border-radius:4px;margin-bottom:4px}
- .support-banner.ok{background:#0d2010;color:#56d364;border:1px solid #1a4020}
- .support-banner.no{background:#2a0d0d;color:#f78166;border:1px solid #401a1a}
- aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}
- .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}
- .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}
- .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}
- .kv .v{color:var(--ui-text)}
- .div{height:1px;background:var(--ui-border)}
- .sr{display:flex;align-items:center;gap:6px;font-size:10px}
- .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}
- .sv{width:38px;text-align:right;color:var(--ui-text)}
- select{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:10px;padding:8px 6px;border-radius:4px;width:100%;min-height:44px}
- .log{display:flex;flex-direction:column;gap:2px}
- .log-row{font-size:9px;color:var(--ui-muted)}
- button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%;min-height:44px}
- @media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}.nav-btn:hover{border-color:var(--ui-accent)}}
- @media(max-width:600px){.layout{flex-direction:column;align-items:stretch}.stage{flex:none}aside{width:100%}:root{--stage-h:480px}}
+ .pstat span{font-size:9px;opacity:.6;text-transform:uppercase;letter-spacing:1px}
+ @media(hover:hover){.nav-btn:hover{border-color:var(--ui-accent)}}
+ /* Short windows leave the page area under 220px: tighter spacing keeps the tallest page inside it with room to spare */
+ @media(max-height:640px){.pc{gap:8px}.gi{padding:12px}}
@media(prefers-reduced-motion:reduce){::view-transition-old(page-content),::view-transition-new(page-content){animation:none}}
</style>
-<style id="ah-inject">
-:root{--ah-bg:rgba(17,17,20,.82);--ah-line:rgba(255,255,255,.1);--ah-ink:#f4f4f2;--ah-muted:#9a9aa2;--ah-accent:#6ea8ff}
-body{padding-top:46px}
-.ah-bar{position:fixed;top:0;left:0;right:0;height:46px;z-index:2147483000;display:flex;align-items:center;justify-content:space-between;gap:10px;padding:0 clamp(10px,3vw,18px);background:var(--ah-bg);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-bottom:1px solid var(--ah-line);font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;box-sizing:border-box}
-.ah-bar a,.ah-bar button{color:var(--ah-muted);text-decoration:none;background:none;border:0;font:inherit;cursor:pointer;display:inline-flex;align-items:center;gap:6px;min-height:34px;padding:0 7px;border-radius:6px;transition:color .18s,background .18s;white-space:nowrap}
-.ah-bar a:hover,.ah-bar button:hover{color:var(--ah-ink)}
-.ah-home{color:var(--ah-ink);font-weight:600}
-.ah-actions{display:flex;align-items:center;gap:2px}
-.ah-sep{width:1px;height:16px;background:var(--ah-line);margin:0 4px}
-.ah-copied{color:var(--ah-accent)!important}
-@media(max-width:600px){.ah-bar .ah-hideSm{display:none}}
-@media print{.ah-bar{display:none}body{padding-top:0}}
-</style>
+ <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=4">
+ <script src="../../../assets/js/demo-page.js?v=4" defer></script>
</head>
-<body>
-<div class="ah-bar" role="navigation" aria-label="Animation Handbook"><a class="ah-home" href="../../../">← Animation Handbook</a><span class="ah-actions"><a class="ah-hideSm" href="../shared-element-transition/" rel="next" title="Next">Next ›</a><span class="ah-sep ah-hideSm"></span><button type="button" id="ah-copy" class="ah-hideSm">Copy source</button><a class="ah-hideSm" href="https://github.com/matinmonshizadeh/animation-handbook/blob/main/animations/03-page-transitions/view-transitions-api/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div>
-<header>
- <h1>View Transitions API</h1>
- <p>document.startViewTransition() — the browser captures before/after and animates automatically.</p>
-</header>
-<div class="layout">
- <div class="stage">
- <nav class="mini-nav" id="nav"></nav>
- <div class="page-area" id="page-area"></div>
- </div>
- <aside>
- <p class="note">View Transitions API wraps any DOM change and the browser handles capture and animation. CSS pseudo-elements ::view-transition-old() and ::view-transition-new() let you customize the choreography.</p>
- <div id="support-banner" class="support-banner ok">✓ Supported in this browser</div>
- <div class="lbl">State</div>
- <div class="kv"><span>Page</span><span class="v" id="cur-page">Home</span></div>
- <div class="div"></div>
- <div class="lbl">Transition style</div>
- <select id="style-sel">
- <option value="crossfade" selected>Crossfade (default)</option>
- <option value="slide">Slide</option>
- <option value="zoom">Zoom</option>
- <option value="custom">Custom (rotate)</option>
- </select>
- <div><div class="lbl" id="dur-lbl">Duration</div>
- <div class="sr"><input type="range" id="dur-sl" aria-labelledby="dur-lbl" min="100" max="2000" value="500" step="50"><span class="sv" id="dur-v">500ms</span></div>
+<body class="hb" data-hb-kind="do" data-hb-autoplay>
+<nav class="hb-bar" aria-label="Animation Handbook">
+ <a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
+ <span class="hb-pager"><a href="../shared-element-transition/" rel="next" aria-label="Next: Shared Element Transition"><span><span class="hb-dir">Next: </span>Shared Element Transition</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
+</nav>
+<main class="hb-page">
+ <header class="hb-head">
+ <p class="hb-cat">03.01 · Page Transitions</p>
+ <h1>View Transitions API</h1>
+ <p class="hb-lede">The browser animates the change between two pages for you. Best for web apps.</p>
+ </header>
+
+ <section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
+ <div class="hb-step-head">
+ <span class="hb-num" aria-hidden="true">1</span>
+ <div><h2 id="hb-watch-title">Click it</h2><p>Click Work or About at the top of the box, or press Show me.</p></div>
+ </div>
+ <div class="stage">
+ <nav class="mini-nav" id="nav" aria-label="Demo pages"></nav>
+ <div class="page-area" id="page-area"></div>
</div>
- <div><div class="lbl">Easing</div>
- <select id="ease-sel">
- <option value="ease-in-out" selected>Ease in-out</option>
- <option value="ease-out">Ease out</option>
- <option value="linear">Linear</option>
- <option value="cubic-bezier(.2,.7,.3,1)">Smooth</option>
- </select>
+ <div class="hb-player">
+ <button class="hb-play" type="button" id="btn-demo" data-hb-demo><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"/></svg>Show me</button>
+ <button class="hb-play" type="button" id="btn-reset" data-hb-reset><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>Reset</button>
+ <label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo autocomplete="off"><span>Slow motion</span></label>
+ </div>
+ </section>
+
+ <section class="hb-step hb-try" aria-labelledby="hb-try-title">
+ <div class="hb-step-head">
+ <span class="hb-num" aria-hidden="true">2</span>
+ <div><h2 id="hb-try-title">Try it</h2><p>Change a setting, then try it again or press Show me.</p></div>
+ </div>
+ <div class="hb-settings">
+ <div class="hb-setting">
+ <p class="hb-setting-name" id="style-lbl">Transition style</p>
+ <div class="seg" id="style-seg" role="group" aria-labelledby="style-lbl">
+ <button type="button" data-style="crossfade" class="on" aria-pressed="true">Fade</button>
+ <button type="button" data-style="slide" aria-pressed="false">Slide</button>
+ <button type="button" data-style="zoom" aria-pressed="false">Zoom</button>
+ <button type="button" data-style="custom" aria-pressed="false">Tilt</button>
+ </div>
+ <p class="hb-hint">The same click, animated four different ways.</p>
+ </div>
+ <div class="hb-setting">
+ <p class="hb-setting-name" id="speed-lbl">Speed</p>
+ <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
+ <button type="button" data-ms="800" aria-pressed="false">Slow</button>
+ <button type="button" data-ms="500" class="on" aria-pressed="true">Normal</button>
+ <button type="button" data-ms="300" aria-pressed="false">Fast</button>
+ </div>
+ <p class="hb-hint">How long the change from page to page takes.</p>
+ </div>
+ </div>
+ <details class="hb-options">
+ <summary><span class="hb-more-label">More options</span><span class="hb-less">Fewer options</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
+ <div class="hb-settings">
+ <div class="hb-setting">
+ <p class="hb-setting-name" id="feel-lbl">Feel</p>
+ <div class="seg" id="feel-seg" role="group" aria-labelledby="feel-lbl">
+ <button type="button" data-ease="ease-out" aria-pressed="false">Smooth</button>
+ <button type="button" data-ease="ease-in-out" class="on" aria-pressed="true">Gentle</button>
+ <button type="button" data-ease="linear" aria-pressed="false">Even</button>
+ </div>
+ <p class="hb-hint">Gentle eases in and out; Even keeps one steady pace.</p>
+ </div>
+ </div>
+ </details>
+ </section>
+
+ <section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
+ <div class="hb-step-head">
+ <span class="hb-num" aria-hidden="true">3</span>
+ <div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div>
</div>
- <div class="div"></div>
- <div class="lbl">History</div>
- <div class="log" id="trans-log"></div>
- <div class="div"></div>
- <button class="rst" id="rst-btn">← Return to Home</button>
- </aside>
-</div>
+ <div class="hb-card">
+ <p class="hb-prompt">Add page transitions to [your site's pages or views] with the browser's View Transitions API. Wrap each page change in a view transition: the browser takes a picture of the page before and after the change and animates between the two pictures. Name the content area so that only it animates, and turn off the default animation of the whole page. Style how the old and new pictures move with CSS, for example a fade, a slide or a zoom. Check that the browser supports the API, and simply swap the content when it does not. If the visitor has reduced motion turned on, swap the content with no animation. Match the settings listed below.</p>
+ <div class="hb-chips-box" hidden>
+ <p class="hb-chips-title">Your settings</p>
+ <ul class="hb-chips"></ul>
+ </div>
+ <div class="hb-copy-row">
+ <button class="hb-copy" type="button"><svg class="hb-ic hb-i-copy" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="hb-ic hb-i-done" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg><span class="hb-copy-label" aria-live="polite">Copy prompt</span></button>
+ <p class="hb-hint">Replace the words in brackets with your own element. Your settings are added at the end.</p>
+ </div>
+ </div>
+ </section>
+
+ <section class="hb-about" aria-labelledby="hb-what-title">
+ <div class="hb-what">
+ <h2 id="hb-what-title">What it is</h2>
+ <div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
+ </div>
+ <div class="hb-fit">
+ <h2>Good for</h2>
+ <ul class="hb-tags hb-good"><li>Web apps</li><li>Page changes</li><li>Tabs and filters</li><li>Galleries</li></ul>
+ <h3>Avoid on</h3>
+ <ul class="hb-tags hb-avoid"><li>Frequent updates</li></ul>
+ </div>
+ </section>
+
+ <section class="hb-related" aria-labelledby="hb-related-title" hidden>
+ <h2 id="hb-related-title">Similar animations</h2>
+ <div class="hb-rel-list"></div>
+ </section>
+</main>
+<footer class="hb-foot"><span>Animation Handbook</span><a href="#top">Back to top ↑</a></footer>
<script>
const PAGES=[
- {name:'Home',bg:'linear-gradient(135deg,#0d1a2e,#192640)',html:`<div class="pc"><div class="pe">Creative Studio</div><h2 class="ph">Design without compromise.</h2><p class="pp">We craft digital products that earn attention and keep it.</p></div>`},
- {name:'Work',bg:'linear-gradient(135deg,#0d1f15,#152e1e)',html:`<div class="pc"><div class="pe">Selected Work</div><h2 class="ph">The Portfolio</h2><div class="pgrid">${['Atlas','Orbit','Prism','Lumen','Frame','Echo'].map(n=>`<div class="gi">${n}</div>`).join('')}</div></div>`},
- {name:'About',bg:'linear-gradient(135deg,#1f0d26,#2e1540)',html:`<div class="pc"><div class="pe">Our Story</div><h2 class="ph">Built on conviction.</h2><p class="pp">18 people who care unreasonably about craft. Independent since 2016.</p><div class="pstat"><div><b>140+</b><span>Projects</span></div><div><b>9</b><span>Years</span></div></div></div>`},
+ {name:'Home',bg:'linear-gradient(135deg,#0d1a2e,#192640)',html:`<div class="pc"><div class="pe">Creative Studio</div><p class="ph">Design without compromise.</p><p class="pp">We craft digital products that earn attention and keep it.</p></div>`},
+ {name:'Work',bg:'linear-gradient(135deg,#0d1f15,#152e1e)',html:`<div class="pc"><div class="pe">Selected Work</div><p class="ph">The Portfolio</p><div class="pgrid">${['Atlas','Orbit','Prism','Lumen','Frame','Echo'].map(n=>`<div class="gi">${n}</div>`).join('')}</div></div>`},
+ {name:'About',bg:'linear-gradient(135deg,#1f0d26,#2e1540)',html:`<div class="pc"><div class="pe">Our Story</div><p class="ph">Built on conviction.</p><p class="pp">18 people who care unreasonably about craft. Independent since 2016.</p><div class="pstat"><div><b>140+</b><span>Projects</span></div><div><b>9</b><span>Years</span></div></div></div>`},
];
- const nav=document.getElementById('nav'),area=document.getElementById('page-area');
- const curPage=document.getElementById('cur-page'),logEl=document.getElementById('trans-log');
- const durSl=document.getElementById('dur-sl'),durV=document.getElementById('dur-v');
- const easeSel=document.getElementById('ease-sel'),styleSel=document.getElementById('style-sel');
- const supportBanner=document.getElementById('support-banner');
+ const root=document.documentElement,stage=document.querySelector('.stage');
+ const nav=document.getElementById('nav'),area=document.getElementById('page-area'),slowTog=document.getElementById('slow-tog');
const supportsVT='startViewTransition' in document;
- let current=0,animating=false,history=[];
const motionOk=!window.matchMedia('(prefers-reduced-motion:reduce)').matches;
-
- if(!supportsVT){supportBanner.className='support-banner no';supportBanner.textContent='✗ Not supported — using crossfade fallback';}
+ // run only ever grows in settle(): a navigation still waiting on its view transition compares it and stops there
+ let current=0,animating=false,style='crossfade',dur=500,run=0,vt=null,afterMove=null,wayBack=0,timers=[];
+ const pages=[],navBtns=[];
PAGES.forEach((p,i)=>{
- const d=document.createElement('div');d.className='page'+(i===0?' active':'');d.id='p'+i;d.style.background=p.bg;d.innerHTML=p.html;d.style.opacity=i===0?'1':'0';area.appendChild(d);
- const b=document.createElement('button');b.className='nav-btn'+(i===0?' active':'');b.textContent=p.name;b.addEventListener('click',()=>navigate(i));nav.appendChild(b);
+ const d=document.createElement('div');d.className='page';d.innerHTML=p.html;area.appendChild(d);pages.push(d);
+ const b=document.createElement('button');b.type='button';b.className='nav-btn';b.textContent=p.name;
+ b.addEventListener('click',()=>navigate(i));nav.appendChild(b);navBtns.push(b);
});
- function updateNav(n){document.querySelectorAll('.nav-btn').forEach((b,i)=>b.classList.toggle('active',i===n));curPage.textContent=PAGES[n].name}
- function addLog(f,t){history.unshift(PAGES[f].name+' → '+PAGES[t].name);if(history.length>3)history.pop();logEl.innerHTML=history.map(l=>`<div class="log-row">${l}</div>`).join('')}
+ // Drops a timer's id once it fires, so `timers` only holds the ones still waiting.
+ function later(fn,wait){
+ const id=setTimeout(()=>{
+ const i=timers.indexOf(id);
+ if(i>-1)timers.splice(i,1);
+ fn();
+ },wait);
+ timers.push(id);
+ return id;
+ }
+ function cancel(id){
+ clearTimeout(id);
+ const i=timers.indexOf(id);
+ if(i>-1)timers.splice(i,1);
+ }
+
+ function updateNav(n){navBtns.forEach((b,i)=>b.classList.toggle('active',i===n))}
+ // The resting state for page n: it shows, the others are hidden, and no transition leaves a style behind
+ function showPage(n){
+ pages.forEach((el,i)=>{
+ el.classList.toggle('active',i===n);
+ el.style.cssText='';
+ el.style.background=PAGES[i].bg;
+ el.style.opacity=i===n?'1':'0';
+ });
+ }
- function switchPage(prev,next){
- document.getElementById('p'+prev).classList.remove('active');document.getElementById('p'+prev).style.opacity='0';
- document.getElementById('p'+next).classList.add('active');document.getElementById('p'+next).style.opacity='1';
+ // Ends a transition: the demo is idle again, and a Show me run goes on to its next step
+ function finish(){
+ animating=false;
+ const then=afterMove;afterMove=null;
+ if(then)then();
+ }
+ // Stops everything at once and shows the resting state for `current`
+ function settle(){
+ timers.forEach(clearTimeout);timers=[];wayBack=0;afterMove=null;
+ run++;
+ if(vt){vt.skipTransition();vt=null}
+ animating=false;
+ updateNav(current);showPage(current);
}
- async function navigate(next){
+ async function navigate(next,then){
if(next===current||animating)return;
- const prev=current;current=next;updateNav(next);addLog(prev,next);
- if(!motionOk){switchPage(prev,next);return;}
+ const prev=current;current=next;updateNav(next);
+ afterMove=then||null;
+ if(!motionOk){showPage(next);finish();return}
animating=true;
- const style=styleSel.value;
- document.documentElement.dataset.vt=style==='crossfade'?'':style;
+ const mine=run,scale=slowTog.checked?3:1;
+ root.dataset.vt=style==='crossfade'?'':style;
+ root.style.setProperty('--vt-dur',dur*scale+'ms');
if(supportsVT){
- const t=document.startViewTransition(()=>switchPage(prev,next));
- t.ready.catch(()=>{}); // a skipped transition (e.g. tab hidden) rejects ready; the DOM change still applies
- await t.finished;
+ // The callback shows the resting state for `current` as it is when it runs, so a skipped transition cannot undo a Reset
+ vt=document.startViewTransition(()=>showPage(current));
+ vt.ready.catch(()=>{}); // a skipped transition (e.g. tab hidden) rejects ready; the DOM change still applies
+ await vt.finished.catch(()=>{});
+ if(mine!==run)return; // Reset or Show me settled the demo meanwhile
+ vt=null;
+ finish();
}else{
- // Fallback crossfade
- const o=document.getElementById('p'+prev),n=document.getElementById('p'+next);
- o.style.transition=`opacity 300ms ease-in-out`;n.style.transition=`opacity 300ms ease-in-out`;
+ // Fallback crossfade for browsers without the API, whatever the style and speed
+ const o=pages[prev],n=pages[next],fade=300*scale;
+ void area.offsetWidth;
+ o.style.transition=n.style.transition=`opacity ${fade}ms ease-in-out`;
o.style.opacity='0';n.style.opacity='1';n.classList.add('active');
- await new Promise(r=>setTimeout(r,350));
- o.classList.remove('active');o.style.cssText='';o.style.background=PAGES[prev].bg;o.style.opacity='0';n.style.cssText='';n.style.background=PAGES[next].bg;
+ later(()=>{showPage(current);finish()},fade+50);
}
- animating=false;
}
- durSl.addEventListener('input',()=>{const d=durSl.value+'ms';durV.textContent=d;document.documentElement.style.setProperty('--vt-dur',d)});
- easeSel.addEventListener('change',()=>document.documentElement.style.setProperty('--vt-ease',easeSel.value));
- document.getElementById('rst-btn').addEventListener('click',()=>{
- if(animating)return;const p=current;current=0;updateNav(0);if(p!==0)addLog(p,0);
- document.querySelectorAll('.page').forEach((el,i)=>{el.classList.toggle('active',i===0);el.style.cssText='';el.style.background=PAGES[i].bg;el.style.opacity=i===0?'1':'0'});animating=false;
- });
+ // Show me: one visit to the next page, a hold of 1200ms, and the way back to where the run started
+ function showMe(){
+ settle();
+ const start=current;
+ navigate((start+1)%PAGES.length,()=>{wayBack=later(()=>{wayBack=0;navigate(start)},1200)});
+ }
+ function reset(){settle();current=0;updateNav(0);showPage(0)}
+
+ document.getElementById('btn-demo').addEventListener('click',showMe);
+ document.getElementById('btn-reset').addEventListener('click',reset);
+ // The visitor took over: cancel what the run has not started yet. A transition already moving finishes on its own.
+ document.addEventListener('hb:input',()=>{afterMove=null;cancel(wayBack);wayBack=0});
+ // While a view transition runs, the browser sends every press to the page root, so the shared script never hears a press on the
+ // stage. A press over the stage then counts as the visitor taking over: it is passed on as the same "hb:input" event.
+ ['pointerdown','click'].forEach(type=>root.addEventListener(type,e=>{
+ if(!vt||!e.isTrusted||e.target!==root)return;
+ const r=stage.getBoundingClientRect();
+ if(e.clientX>=r.left&&e.clientX<=r.right&&e.clientY>=r.top&&e.clientY<=r.bottom)document.dispatchEvent(new CustomEvent('hb:input',{detail:{type}}));
+ },{capture:true,passive:true}));
+
+ function choices(id,pick){
+ const buttons=document.querySelectorAll('#'+id+' button');
+ buttons.forEach(b=>b.addEventListener('click',()=>{
+ buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
+ pick(b.dataset);
+ }));
+ }
+ choices('style-seg',d=>{style=d.style});
+ choices('speed-seg',d=>{dur=+d.ms});
+ choices('feel-seg',d=>root.style.setProperty('--vt-ease',d.ease));
+ showPage(0);updateNav(0);
</script>
-<script>(function(){var b=document.getElementById("ah-copy");if(!b)return;b.addEventListener("click",function(){fetch(location.href).then(function(r){return r.text();}).catch(function(){return document.documentElement.outerHTML;}).then(function(t){return navigator.clipboard.writeText(t);}).then(function(){b.textContent="Copied!";b.classList.add("ah-copied");setTimeout(function(){b.textContent="Copy source";b.classList.remove("ah-copied");},1500);}).catch(function(){b.textContent="Copy failed";setTimeout(function(){b.textContent="Copy source";},1500);});});})();</script>
</body>
</html>
diff --git a/index.html b/index.html
index 4d518cf1..ec19c627 100644
--- a/index.html
+++ b/index.html
@@ -932,7 +932,7 @@ const CATS=[
desc:'Full-page transitions between routes or views — crossfades, slides, portals, morphs, and the browser-native API.',
folder:'animations/03-page-transitions',
entries:[
- ['view-transitions-api','View Transitions API','document.startViewTransition() — the browser captures before/after and animates automatically.'],
+ ['view-transitions-api','View Transitions API','The browser animates the change between two pages for you. Best for web apps.'],
['shared-element-transition','Shared Element Transition','A thumbnail morphs continuously into a detail hero as pages change — the FLIP technique applied.'],
['morph-transition','Morph Transition','An SVG path morphs between page-specific shapes — point-by-point interpolation across 12-vertex paths.'],
['crossfade','Crossfade','Both pages visible simultaneously at ~50% opacity mid-transition — compare with sequential fade.'],