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.
HTML ai-promptsanimationcss-animationsfrontendgithub-pagesjavascriptmicrointeractionsmotion-designno-dependenciesreferencescroll-animationui-animationweb-animationweb-developmentwebgl
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Letter-by-Letter Stagger — Animation Handbook</title>
<meta name="description" content="A phrase appears letter by letter or typewriter-style. Best for short headlines.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/02-entrance-and-exit/letter-by-letter-stagger/">
<link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
<link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
<link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
<meta property="og:type" content="article">
<meta property="og:site_name" content="Animation Handbook">
<meta property="og:title" content="Letter-by-Letter Stagger — Animation Handbook">
<meta property="og:description" content="A phrase appears letter by letter or typewriter-style. Best for short headlines.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/02-entrance-and-exit/letter-by-letter-stagger/">
<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="Letter-by-Letter Stagger — Animation Handbook">
<meta name="twitter:description" content="A phrase appears letter by letter or typewriter-style. Best for short headlines.">
<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": "Letter-by-Letter Stagger", "name": "Letter-by-Letter Stagger", "description": "A phrase appears letter by letter or typewriter-style. Best for short headlines.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/02-entrance-and-exit/letter-by-letter-stagger/", "inLanguage": "en", "articleSection": "Entrance & Exit", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Entrance & Exit, Letter-by-Letter Stagger"}</script>
<style>
:root{--ui-accent:#5fd88a;--dur:400ms;--ease:ease-out;--stagger:35ms}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
.stage{display:flex;align-items:center;justify-content:center;overflow:hidden;background:#0b0b0d;padding:clamp(20px,4vw,48px)}
#text-target,.cmp-text{font-size:clamp(26px,5vw,56px);font-weight:bold;text-align:center;line-height:1.2;max-width:560px;word-break:break-word;position:relative}
/* cascade mode */
.char{display:inline-block}
[data-mode="cascade"] .char{opacity:0;transition:opacity var(--dur) var(--ease) calc(var(--i)*var(--stagger)),transform var(--dur) var(--ease) calc(var(--i)*var(--stagger))}
[data-mode="cascade"][data-anim="fade-up"] .char{transform:translateY(0.4em)}
[data-mode="cascade"][data-anim="scale"] .char{transform:scale(0.3)}
[data-mode="cascade"][data-anim="rotate"] .char{transform:rotateY(90deg)}
[data-mode="cascade"].done .char{opacity:1;transform:none}
/* typewriter mode: typed text keeps a typewriter font */
#text-target[data-mode="typewriter"],.cmp-text[data-mode="typewriter"]{font-family:monospace}
[data-mode="typewriter"] .char{opacity:0}
[data-mode="typewriter"] .char.visible{opacity:1}
.cursor{display:inline-block;width:3px;height:0.85em;background:var(--ui-accent);vertical-align:text-bottom;margin-left:2px;animation:blink 1s step-end infinite}
.cursor.hidden{display:none}
@keyframes blink{0%,50%{opacity:1}51%,100%{opacity:0}}
/* See inside and Compare */
.stage{position:relative}
.key,.bars,.cmp-text,.half,.moment,.hold{display:none}
.lbl{padding:3px 8px;border-radius:5px;background:rgba(11,11,13,.9);color:#f4f4f2;font:600 13px/1.25 var(--hb-font)}
.half,.moment{white-space:nowrap}
.cursor.still,.cmp-text .cursor{animation:none}
.cmp-text .cursor{visibility:hidden}
.bars{position:absolute;inset:0;pointer-events:none}
.bars i{position:absolute;height:4px;border-radius:2px;overflow:hidden;background:rgba(244,244,242,.22)}
.bars b{display:block;height:100%;background:var(--ui-accent);transform:scaleX(0);transform-origin:0 50%}
.key{list-style:none;justify-items:start;gap:4px}
.key-row{display:inline-flex;align-items:center;gap:8px}
.sw{flex:none;display:inline-flex;gap:2px;align-items:center;justify-content:center;width:26px}
.sw b{--f:100%;display:block;width:7px;height:4px;border-radius:2px;background:linear-gradient(to right,var(--ui-accent) var(--f),rgba(244,244,242,.3) var(--f))}
.k2 b,.k3 b{width:20px}.k1 b:nth-child(2){--f:60%}.k1 b:nth-child(3){--f:20%}.k2 b{--f:55%}.k3 b{--f:0%}
.sw-dial{flex:none;width:16px;height:16px;margin:0 5px;border:1.5px solid var(--ui-accent);border-radius:50%;background:conic-gradient(var(--ui-accent) 0 72deg,transparent 0)}
.stage[data-hb-mode="inside"]{flex-direction:column;gap:clamp(8px,2vw,16px);padding:clamp(12px,2.5vw,24px) clamp(20px,4vw,48px)}
.stage[data-hb-mode="inside"] #text-target{z-index:1;font-size:var(--fs);width:calc(var(--tw)*1em);max-width:none;flex:none}
.stage[data-hb-mode="inside"] .bars{display:block}
.stage[data-hb-mode="inside"] .bars .on b,.stage[data-hb-mode="inside"] .bars.go b{transform:none}
.stage[data-hb-mode="inside"] .bars.go b{transition:transform var(--dur) var(--ease) calc(var(--i)*var(--stagger))}
.stage[data-hb-mode="inside"] .key{display:grid}
.stage[data-hb-mode="inside"] #text-target[data-mode="typewriter"]~.key :is(.k2 b,.k1 b:nth-child(2)){--f:100%}
.stage[data-hb-mode="inside"] #text-target[data-mode="typewriter"]~.key .k1 b:nth-child(3){--f:0%}
.stage[data-hb-mode="inside"]:not(.posed) .k4{visibility:hidden}
.stage[data-hb-mode="compare"]{--nr:34px;--px:clamp(6px,2vw,18px);display:grid;grid-template-columns:repeat(2,minmax(0,1fr));
grid-template-rows:var(--nr) minmax(0,1fr) var(--nr);align-items:center;padding:0}
.stage[data-hb-mode="compare"]::after{content:'';position:absolute;top:0;bottom:var(--nr);left:50%;border-left:1px solid rgba(244,244,242,.22)}
.stage[data-hb-mode="compare"]>.cmp-text,.stage[data-hb-mode="compare"] #text-target{display:block;font-size:var(--fs);width:calc(var(--tw)*1em);max-width:none;min-width:0;margin:0 var(--px);justify-self:center}
.stage[data-hb-mode="compare"]>.cmp-text{grid-area:2/1}.stage[data-hb-mode="compare"] #text-target{grid-area:2/2}
.stage[data-hb-mode="compare"] .half,.stage[data-hb-mode="compare"] .moment{display:block}
.stage[data-hb-mode="compare"] .half{justify-self:start;margin-left:8px}
.stage[data-hb-mode="compare"] .half.first{grid-area:1/1}.stage[data-hb-mode="compare"] .half.second{grid-area:1/2}
.stage[data-hb-mode="compare"] .moment{grid-area:3/1/4/3;justify-self:center}
.stage[data-hb-mode="compare"]:not(.posed) .moment{visibility:hidden}
.stage[data-hb-mode="inside"] .hold,.stage[data-hb-mode="compare"] .hold{display:flex;position:absolute;left:0;right:0;top:0;visibility:hidden;pointer-events:none;
align-items:center;justify-content:center;padding:clamp(20px,4vw,48px)}
.hold .cmp-text{display:block}
@media(min-width:760px){.stage[data-hb-mode="inside"] .key{grid-template-columns:repeat(2,minmax(0,auto));gap:6px 20px}}
@media(max-width:600px){.lbl{font-size:12.5px;padding:3px 6px}}
@media(prefers-reduced-motion:reduce){.char{transition:none!important;opacity:1!important;transform:none!important}.bars b{transition:none!important}}
</style>
<link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
<script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="once" 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="../split-text-reveal/" rel="prev" aria-label="Previous: Split Text Reveal"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Split Text Reveal</span></a><a href="../word-by-word-reveal/" rel="next" aria-label="Next: Word-by-Word Reveal"><span><span class="hb-dir">Next: </span>Word-by-Word Reveal</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
<a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
<header class="hb-head">
<p class="hb-cat">02.08 · Entrance & Exit</p>
<h1>Letter-by-Letter Stagger</h1>
<p class="hb-lede">A phrase appears letter by letter or typewriter-style. Best for short headlines.</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">Watch it</h2><p>It plays by itself. Turn on slow motion to see each part of the movement.</p></div>
</div>
<div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
<button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
<button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
<button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
</div>
<div class="stage hb-dots hb-grow">
<div id="text-target" data-mode="cascade" data-anim="fade-up">Hello, world.</div>
<div class="bars" aria-hidden="true"></div>
<ul class="key" aria-hidden="true">
<li class="lbl key-row k1" data-hb-caption><span class="sw"><b></b><b></b><b></b></span><span>Each letter waits a little longer than the one before</span></li>
<li class="lbl key-row k2" data-hb-caption><span class="sw"><b></b></span><span>Bars: how far each letter has come</span></li>
<li class="lbl key-row k3" data-hb-caption><span class="sw"><b></b></span><span>Still waiting</span></li>
<li class="lbl key-row k4" data-hb-caption><i class="sw-dial"></i><span>A fifth of a second in</span></li>
</ul>
<div class="cmp-text" aria-hidden="true" inert></div>
<p class="lbl half first" aria-hidden="true" data-hb-caption>All at once</p>
<p class="lbl half second" aria-hidden="true" data-hb-caption>Letter by letter</p>
<p class="lbl moment" aria-hidden="true" data-hb-caption>A fifth of a second in</p>
<div class="hold" aria-hidden="true" inert><div class="cmp-text"></div></div>
</div>
<div class="hb-player">
<button class="hb-play" type="button" id="btn-play" data-hb-replay><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>Replay</button>
<label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="loop-tog" data-hb-loop autocomplete="off"><span>Loop</span></label>
<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>
<div class="hb-mode-notes" aria-live="polite">
<p data-hb-for="inside" hidden>Inside, the bar under each letter fills as that letter arrives. Each one starts a little after the one before, so the bars fill like a wave.</p>
<p data-hb-for="compare" hidden>All at once plays every letter together; Letter by letter starts each a moment after the last, so the phrase builds up. With Loop off, both rest a fifth of a second in.</p>
</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 and the animation plays again.</p></div>
</div>
<div class="hb-settings">
<div class="hb-setting">
<p class="hb-setting-name" id="style-lbl">Style</p>
<div class="seg" id="style-seg" role="group" aria-labelledby="style-lbl">
<button type="button" data-mode="cascade" class="on" aria-pressed="true">Cascade</button>
<button type="button" data-mode="typewriter" aria-pressed="false">Typewriter</button>
</div>
<p class="hb-hint">Cascade animates each letter; Typewriter types them.</p>
</div>
<div class="hb-setting">
<p class="hb-setting-name" id="stagger-lbl">Delay between letters</p>
<div class="seg" id="stagger-seg" role="group" aria-labelledby="stagger-lbl">
<button type="button" data-stagger="20" aria-pressed="false">Short</button>
<button type="button" data-stagger="35" class="on" aria-pressed="true">Medium</button>
<button type="button" data-stagger="80" aria-pressed="false">Long</button>
</div>
<p class="hb-hint">Longer delays feel slower and more theatrical.</p>
</div>
<div class="hb-setting" id="anim-setting">
<p class="hb-setting-name" id="anim-lbl">How each letter appears</p>
<div class="seg" id="anim-seg" role="group" aria-labelledby="anim-lbl">
<button type="button" data-anim="fade-up" class="on" aria-pressed="true">Fade up</button>
<button type="button" data-anim="fade" aria-pressed="false">Fade</button>
<button type="button" data-anim="scale" aria-pressed="false">Grow</button>
<button type="button" data-anim="rotate" aria-pressed="false">Flip</button>
</div>
<p class="hb-hint">The small entrance every letter plays.</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" id="speed-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="650" aria-pressed="false">Slow</button>
<button type="button" data-ms="400" class="on" aria-pressed="true">Normal</button>
<button type="button" data-ms="250" aria-pressed="false">Fast</button>
</div>
<p class="hb-hint">How long each letter takes to settle.</p>
</div>
<div class="hb-setting" id="cursor-setting" hidden>
<label class="hb-switch-row"><span>Blinking cursor</span><input class="hb-switch" type="checkbox" role="switch" id="cursor-tog" checked autocomplete="off"></label>
<p class="hb-hint">A cursor leads the letters as they are typed.</p>
</div>
<div class="hb-setting">
<label class="hb-setting-name" for="txt-in">Your text</label>
<input class="hb-text" type="text" id="txt-in" value="Hello, world." maxlength="60" autocomplete="off">
<p class="hb-hint">Short phrases work best, up to 60 characters.</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="hb-card">
<p class="hb-prompt">Add a letter-by-letter entrance to [a short phrase or headline]. In the cascade style, every letter plays a small entrance a moment after the previous one, so the phrase assembles from left to right. In the typewriter style, the letters appear one at a time as if someone is typing, with a blinking cursor when the settings include one. Use it only on short phrases, because long text becomes tedious to wait for. Screen readers should hear the whole phrase once, not letter by letter. If the visitor has reduced motion turned on, show the full phrase immediately. 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>
<div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></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>Short headlines</li><li>Names and logos</li><li>Chat messages</li><li>Loading screens</li></ul>
<h3>Avoid on</h3>
<ul class="hb-tags hb-avoid"><li>Long text</li><li>Buttons and labels</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="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
const target=document.getElementById('text-target');
const vars=document.documentElement.style;
const loopTog=document.getElementById('loop-tog'),slowTog=document.getElementById('slow-tog');
const animSetting=document.getElementById('anim-setting'),speedSetting=document.getElementById('speed-setting'),cursorSetting=document.getElementById('cursor-setting');
const cursorTog=document.getElementById('cursor-tog'),txtIn=document.getElementById('txt-in');
const motionOk=!window.matchMedia('(prefers-reduced-motion:reduce)').matches;
let mode='cascade',anim='fade-up',ms=400,stagger=35,timers=[];
const stage=document.querySelector('.stage'),bars=stage.querySelector('.bars'),cmp=stage.querySelector('.cmp-text'),key=stage.querySelector('.key');
const hold=stage.querySelector('.hold'),holdBox=hold.firstElementChild,notes=[...document.querySelectorAll('[data-hb-for]')],marked=notes.map(n=>n.textContent),POSE_MS=200;
let view='normal',posed=false,busyUntil=0,sig='';
function dur(){return slowTog.checked?ms*3:ms}
function stag(){return slowTog.checked?stagger*3:stagger}
function apply(){
vars.setProperty('--dur',dur()+'ms');
vars.setProperty('--stagger',stag()+'ms');
}
// Rebuilds the letters (and the cursor, in Typewriter), hidden, from the current style, cursor choice and text
function buildSpans(){
target.classList.remove('done');cmp.classList.remove('done');bars.classList.remove('go');
const text=txtIn.value||'Hello, world.';
target.dataset.mode=mode;target.dataset.anim=anim;
target.innerHTML='';
[...text].forEach((c,i)=>{
const s=document.createElement('span');
s.className='char';s.style.setProperty('--i',i);
s.textContent=c===' '?'\u00a0':c; // a lone plain space would collapse inside its inline-block
target.appendChild(s);
});
if(mode==='typewriter'&&cursorTog.checked){
const cur=document.createElement('span');cur.className='cursor hidden';cur.id='cursor';
target.appendChild(cur);
}
draw();
}
function later(fn,wait){timers.push(setTimeout(fn,wait))}
function playLen(){
const n=target.querySelectorAll('.char').length;
return mode==='cascade'?n*stag()+dur():n*stag();
}
function playCascade(){
// rebuild the letters hidden, then show them after a reflow, so every play settles them in from the start
buildSpans();void target.offsetWidth;
target.classList.add('done');cmp.classList.add('done');bars.classList.add('go');
}
function playTypewriter(){
if(!motionOk){
target.querySelectorAll('.char').forEach(c=>c.classList.add('visible'));
return;
}
const chars=[...target.querySelectorAll('.char')];
const cur=target.querySelector('.cursor');
chars.forEach(c=>c.classList.remove('visible'));
if(cur)cur.classList.remove('hidden');
chars.forEach((c,i)=>later(()=>{c.classList.add('visible');if(bars.children[i])bars.children[i].classList.add('on')},i*stag()));
if(view!=='normal'){
const all=[...cmp.querySelectorAll('.char')];
all.forEach(c=>c.classList.remove('visible'));[...bars.children].forEach(b=>b.classList.remove('on'));
later(()=>all.forEach(c=>c.classList.add('visible')),60);
}
later(()=>{if(cur)cur.classList.add('hidden')},chars.length*stag());
}
// One play reveals the phrase; while Loop is on it holds, clears at once, waits and plays again
function cycle(){
apply();unpose();
if(mode==='cascade')playCascade();else playTypewriter();
const len=playLen();
busyUntil=motionOk?performance.now()+len:0;
if(!motionOk){if(view!=='normal')poseNow();return}
if(!loopTog.checked){later(restPose,len+700);return}
later(()=>{
if(!loopTog.checked)return;
buildSpans();
later(cycle,400);
},len+1000);
}
function play(){timers.forEach(clearTimeout);timers=[];cycle()}
document.getElementById('btn-play').addEventListener('click',play);
loopTog.addEventListener('change',()=>{if(loopTog.checked)play();else later(restPose,Math.max(0,busyUntil-performance.now())+700)});
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=>{
mode=d.mode;
animSetting.hidden=mode!=='cascade';
speedSetting.hidden=mode!=='cascade';
cursorSetting.hidden=mode!=='typewriter';
buildSpans();
});
choices('stagger-seg',d=>{stagger=+d.stagger});
choices('anim-seg',d=>{anim=d.anim;target.dataset.anim=anim});
choices('speed-seg',d=>{ms=+d.ms});
cursorTog.addEventListener('change',buildSpans);
txtIn.addEventListener('input',buildSpans);
document.querySelector('.hb-try').addEventListener('click',refresh);
slowTog.addEventListener('change',refresh);
// ── See inside and Compare ──
// With Loop off, and always under reduced motion, both views rest a fifth of a second in, worked out from the speed, delay and style
const set=(e,k,v)=>e.style.setProperty(k,v,'important');
const bez=(a,b,t)=>3*a*t*(1-t)**2+3*b*t*t*(1-t)+t**3;
function progress(x){ // the page's ease-out; t found by halving
let lo=0,hi=1,t;x=Math.min(1,x);
if(x<=0)return 0;
for(let i=0;i<30;i++){t=(lo+hi)/2;if(bez(0,.58,t)<x)lo=t;else hi=t}
return bez(0,1,t);
}
function poseOne(el,p){
set(el,'transition','none');
if(mode==='typewriter'){set(el,'opacity',p?'1':'0');return}
set(el,'opacity',p.toFixed(3));
set(el,'transform',anim==='fade-up'?`translateY(${(.4*(1-p)).toFixed(3)}em)`:anim==='scale'?`scale(${(.3+.7*p).toFixed(3)})`:anim==='rotate'?`rotateY(${(90*(1-p)).toFixed(1)}deg)`:'none');
}
function poseNow(){
const d=dur(),s=stag(),tw=mode==='typewriter';
const share=i=>tw?(i*s<=POSE_MS?1:0):progress((POSE_MS-i*s)/d);
target.querySelectorAll('.char').forEach((c,i)=>poseOne(c,share(i)));
cmp.querySelectorAll('.char').forEach(c=>poseOne(c,tw?1:progress(POSE_MS/d)));
[...bars.children].forEach((b,i)=>{set(b.firstChild,'transition','none');set(b.firstChild,'transform',`scaleX(${share(i)})`)});
target.querySelector('.cursor')?.classList.replace('hidden','still');
posed=true;stage.classList.add('posed');describe();
}
function unpose(){ // the phrase is shown as it now is, at once (only posed letters snap)
if(!posed)return;
posed=false;stage.classList.remove('posed');
const all=[...target.querySelectorAll('.char'),...cmp.querySelectorAll('.char'),...bars.querySelectorAll('b')];
all.forEach(e=>{e.style.removeProperty('opacity');e.style.removeProperty('transform')});
void target.offsetWidth;
all.forEach(e=>e.style.removeProperty('transition'));
target.querySelector('.cursor')?.classList.replace('still','hidden');
describe();
}
function restPose(){
if(view==='normal'||posed||(loopTog.checked&&motionOk)||performance.now()<busyUntil-5)return;
poseNow();
}
// Copies are clones of the real letters without ids; the cursor becomes an unseen space of its size so both phrases wrap alike
function fillCopy(el,flat){
el.dataset.mode=mode;el.dataset.anim=anim;
el.replaceChildren(...[...target.children].map(c=>{
const n=c.cloneNode(true);n.removeAttribute('id');
if(c.classList.contains('cursor'))n.className='cursor';
else if(flat)n.style.setProperty('--i',0);
return n;
}));
}
function drawBars(){
bars.replaceChildren();
if(view!=='inside')return;
const ox=target.offsetLeft,oy=target.offsetTop;
bars.classList.toggle('go',mode==='cascade'&&target.classList.contains('done'));
[...target.querySelectorAll('.char')].forEach((c,i)=>{
const b=document.createElement('i');
b.style.cssText=`left:${ox+c.offsetLeft+1}px;top:${oy+c.offsetTop+c.offsetHeight+1}px;width:${Math.max(2,c.offsetWidth-2)}px;--i:${i}`;
b.hidden=c.textContent==='\u00a0';
b.classList.toggle('on',mode==='typewriter'&&c.classList.contains('visible'));
b.appendChild(document.createElement('b'));
bars.appendChild(b);
});
}
// A hidden copy at Normal's size gives the box height and the phrase's width in em, so both views keep Normal's height and line
// breaks while the text is drawn smaller
function layoutFit(){
const cmpv=view==='compare',cs=getComputedStyle(stage),bw=stage.offsetHeight-stage.clientHeight,H=Math.max(parseFloat(cs.minHeight)||0,hold.offsetHeight+bw);
const fn=parseFloat(getComputedStyle(holdBox).fontSize),wn=holdBox.offsetWidth,hn=holdBox.offsetHeight;
stage.style.height=H+'px';
stage.style.setProperty('--tw',(wn/fn+.01).toFixed(4));
const availH=cmpv?H-bw-2*parseFloat(cs.getPropertyValue('--nr')):H-bw-parseFloat(cs.paddingTop)-parseFloat(cs.paddingBottom)-parseFloat(cs.rowGap)-key.offsetHeight;
const availW=cmpv?stage.clientWidth/2-2*parseFloat(getComputedStyle(target).marginLeft):wn;
stage.style.setProperty('--fs',(fn*Math.max(.3,Math.min(1,availH/hn,availW/wn))).toFixed(2)+'px');
sig=stage.clientWidth+'/'+hold.offsetHeight;
drawBars();
}
// The notes say what the box shows now; a still note only while the box rests
function describe(){
const tw=mode==='typewriter',still=!motionOk&&posed,tail=tw&&cursorTog.checked?', and the cursor waits at the end.':'.',S='Shown still, a fifth of a second in: ';
const words=[
still?S+(tw?'the first letters are typed, their bars full'+tail:'the bar under each letter shows how far it has come, each a little behind the one before.')
:tw?'Inside, each letter is typed in turn: its bar fills at once when it appears'+tail:marked[0],
still?S+(tw?'All at once shows the whole phrase, while Letter by letter has typed only its first letters.':'All at once has every letter part way, while Letter by letter has its first letters part way and the rest waiting.')
:tw?'All at once shows the whole phrase together; Letter by letter types it one letter at a time. With Loop off, both rest a fifth of a second in.':marked[1]];
notes.forEach((n,i)=>{if(n.textContent!==words[i])n.textContent=words[i]});
}
// Rebuilds both views from the page's state
function draw(){
if(view==='normal'){['height','--fs','--tw'].forEach(k=>stage.style.removeProperty(k));bars.replaceChildren();cmp.replaceChildren();holdBox.replaceChildren();return}
fillCopy(cmp,true);fillCopy(holdBox,false);
cmp.classList.toggle('done',target.classList.contains('done'));
stage.querySelector('.k2 span:not(.sw)').textContent=mode==='typewriter'?'Typed one at a time: each letter just appears':'Bars: how far each letter has come';
layoutFit();
if(posed)poseNow();else describe();
}
function refresh(){
if(view==='normal')return;
cmp.dataset.anim=holdBox.dataset.anim=anim;
posed?poseNow():describe();
}
document.addEventListener('hb:mode',e=>{
view=e.detail.mode;
if(view==='normal')unpose();
draw();
if(view!=='normal'&&!posed)restPose();
});
const refit=()=>{if(view!=='normal'&&sig!==stage.clientWidth+'/'+hold.offsetHeight){layoutFit();if(posed)poseNow()}};
new ResizeObserver(refit).observe(stage);
document.fonts&&document.fonts.ready.then(draw);
buildSpans();
</script>
</body>
</html>