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
feat: move Text Morphing to the guided-steps page
matin59161be75b14
diff --git a/animations/05-text-typography/text-morphing/README.md b/animations/05-text-typography/text-morphing/README.mdindex a6f33703..b02c00b9 100644--- a/animations/05-text-typography/text-morphing/README.md+++ b/animations/05-text-typography/text-morphing/README.md@@ -1,7 +1,7 @@# Text Morphing## What it is-Text morphing transitions one word into another by animating individual characters out and new characters in. Each character slides out in one direction while its replacement slides in from the opposite direction, with staggered delays creating a wave-like effect across the word. When words have different lengths, extra characters appear or disappear independently.+Text morphing changes one word into the next, letter by letter. The letters of the current word slide out of sight, then the letters of the next word slide in from the opposite side; a small delay between letters can send each change across the word like a wave. Each word stays still long enough to read before the next change.## When to use it- A single changing word in a static phrase: "We make [websites / apps / brands]"@@ -64,19 +64,20 @@ function morphTo(container, toWord, dir = 'up') {## Key parameters| Parameter | Default | Effect ||-----------|---------|--------|-| Morph duration | 400ms | Per-character animation time — 200ms feels snappy, 600ms feels cinematic |-| Stagger per char | 0–80ms | 0 = all chars move simultaneously; 40–60ms creates a readable wave |-| Pause between words | 1500ms | How long each word holds before the next morph — must be long enough to read |-| Direction | Up | Up/down for carousel-style; left/right for slide-style; pick one and stay consistent |+| Slide direction | Up | Up and down look like a slot machine; left and right slide sideways |+| Delay between letters | None | The gap between one letter moving and the next: none, short (30ms) or long (60ms); none moves every letter together, a delay makes a wave |+| Speed | Normal | How long each letter takes to slide: slow is 650ms, normal 400ms and fast 250ms |+| Time on each word | Medium | How long each word stays: short is 900ms, medium 1500ms and long 2400ms; it must be long enough to read |+| Your words, one per line | OCEAN, RIVER, STORM, LIGHT, SOUND | The words that take turns, shown in capitals |## Production notes-- **Length mismatch**: when word A has 5 chars and word B has 8, the extra 3 chars need to fade in from nothing. When B is shorter, 3 chars of A must disappear. The simplest approach: extra chars exit/enter with a 0-width transition or opacity-only fade, so they don't affect the layout of surrounding characters.+- **Length mismatch**: this demo sidesteps it — the whole old word leaves before the new one arrives, so words of any length work. A morph that swaps letters in place has to fade the extra letters in or out with opacity only, so the letters around them do not jump.- **Fixed-width container**: to prevent layout shift as word length changes, give the rotating word container a fixed or `min-width` based on the longest word. Otherwise sibling elements jump as words swap.- **`will-change: transform`**: only add this during active morphing — set it at the start of a transition and remove it after. Persistent `will-change` on many small spans wastes GPU memory.- **GSAP**: `gsap.to(chars, { y: -50, opacity: 0, stagger: 0.03, duration: 0.4 })` for exits, then rebuild and animate in. GSAP's stagger model is cleaner than per-element `transitionDelay` in JavaScript.- **SplitType**: a lightweight library that splits text into `<div>` wrappers per word/char without the overhead of GSAP. Pairs well with this pattern.## See also-- [Rotate Word Carousel](../rotate-word-carousel/) — the same concept with a simpler whole-word slide (no character splitting)-- [Scramble / Glitch Text](../scramble-text/) — random characters before settling, rather than a directional transition-- [Typewriter Effect](../typewriter-effect/) — character-by-character reveal in reading order+- [Rotate Word Carousel](../rotate-word-carousel/) — the whole word slides, with no letters split+- [Scramble / Glitch Text](../scramble-text/) — random symbols lock into the real text+- [Typewriter Effect](../typewriter-effect/) — text typed one character at a timediff --git a/animations/05-text-typography/text-morphing/index.html b/animations/05-text-typography/text-morphing/index.htmlindex de46a4ff..18c97177 100644--- a/animations/05-text-typography/text-morphing/index.html+++ b/animations/05-text-typography/text-morphing/index.html@@ -4,7 +4,7 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Text Morphing — Animation Handbook</title>- <meta name="description" content="One word transitions into another character-by-character — each letter slides out as the next slides in.">+ <meta name="description" content="One word changes into the next, letter by letter. Best for short labels."><link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/05-text-typography/text-morphing/"><link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png"><link rel="icon" type="image/svg+xml" href="../../../favicon.svg">@@ -12,37 +12,25 @@<meta property="og:type" content="article"><meta property="og:site_name" content="Animation Handbook"><meta property="og:title" content="Text Morphing — Animation Handbook">- <meta property="og:description" content="One word transitions into another character-by-character — each letter slides out as the next slides in.">+ <meta property="og:description" content="One word changes into the next, letter by letter. Best for short labels."><meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/05-text-typography/text-morphing/"><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="Text Morphing — Animation Handbook">- <meta name="twitter:description" content="One word transitions into another character-by-character — each letter slides out as the next slides in.">+ <meta name="twitter:description" content="One word changes into the next, letter by letter. Best for short labels."><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": "Text Morphing", "name": "Text Morphing", "description": "One word transitions into another character-by-character — each letter slides out as the next slides in.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/05-text-typography/text-morphing/", "inLanguage": "en", "articleSection": "Text & Typography", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Text & Typography, Text Morphing"}</script>+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Text Morphing", "name": "Text Morphing", "description": "One word changes into the next, letter by letter. Best for short labels.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/05-text-typography/text-morphing/", "inLanguage": "en", "articleSection": "Text & Typography", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Text & Typography, Text Morphing"}</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:#ff6f8b;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:620px;--morph-dur:400ms;--pause-dur:1500ms;--stagger:0ms}+ :root{--ui-accent:#ff6f8b;--morph-dur:400ms}*,*::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:#08080a;overflow:hidden;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:20px;padding:32px}- .morph-label{font-size:10px;letter-spacing:3px;text-transform:uppercase;color:var(--ui-muted)}- /* Word display area */- .morph-stage{height:clamp(80px,12vw,130px);display:flex;align-items:center;justify-content:center;overflow:visible;position:relative;min-width:200px}- .morph-word{position:absolute;display:flex;align-items:center;gap:0;top:50%;transform:translateY(-50%)}+ .stage{display:flex;align-items:center;justify-content:center;position:relative;background:#08080a;overflow:hidden}+ .morph-word{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);display:flex;align-items:center;gap:0;font-size:clamp(56px,9vw,100px)}.morph-char{- font-family:Georgia,'Times New Roman',serif;- font-size:clamp(56px,9vw,100px);+ font-weight:700;line-height:1;color:#fff;display:inline-block;+ white-space:pre;will-change:transform,opacity;transition:transform var(--morph-dur) cubic-bezier(.4,0,.2,1),opacity var(--morph-dur) ease}@@ -54,190 +42,255 @@.morph-char.enter-from-above{transform:translateY(-100%);opacity:0}.morph-char.enter-from-left{transform:translateX(-80%);opacity:0}.morph-char.enter-from-right{transform:translateX(80%);opacity:0}- /* Word cycle indicator */- .cycle-dots{display:flex;gap:6px}- .cycle-dot{width:6px;height:6px;border-radius:50%;background:var(--ui-border);transition:background .2s}- .cycle-dot.active{background:var(--ui-accent)}- /* Panel */- 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:44px;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}- textarea{background:var(--ui-bg);border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:10px;padding:8px;border-radius:4px;width:100%;resize:vertical;min-height:88px;line-height:1.5;outline:none}- textarea:focus{border-color:var(--ui-accent)}- 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)}}- @media(max-width:600px){.layout{flex-direction:column;align-items:stretch}aside{width:100%}:root{--stage-h:auto}.stage{height:auto;min-height:400px}}@media(prefers-reduced-motion:reduce){.morph-char{transition:none!important;transform:none!important;opacity:1!important}}</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:44px;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=3">+ <script src="../../../assets/js/demo-page.js?v=3" 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="../marquee-ticker/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../text-gradient-animation/" 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/05-text-typography/text-morphing/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div>-<header>- <h1>Text Morphing</h1>- <p>One word transitions into another character-by-character — each letter slides out as the next slides in.</p>-</header>-<div class="layout">- <div class="stage">- <div class="morph-label">Morphing</div>- <div class="morph-stage" id="morph-stage" aria-live="polite">+<body class="hb" data-hb-kind="loop">+<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="../marquee-ticker/" rel="prev" aria-label="Previous: Marquee / Ticker"><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>Marquee / Ticker</span></a><a href="../text-gradient-animation/" rel="next" aria-label="Next: Text Gradient Animation"><span><span class="hb-dir">Next: </span>Text Gradient Animation</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">05.07 · Text & Typography</p>+ <h1>Text Morphing</h1>+ <p class="hb-lede">One word changes into the next, letter by letter. Best for short labels.</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 moves by itself. Pause it to look closely, or turn on slow motion to see each part of the movement.</p></div>+ </div>+ <div class="stage hb-dots" id="stage"><div class="morph-word" id="current-word"></div></div>- <div class="cycle-dots" id="dots"></div>- </div>- <aside>- <p class="note">For words of different lengths, extra characters fade independently. Keep word lengths similar to minimize the layout shift during transition.</p>- <div class="lbl">Morph Duration</div>- <div class="sr"><input type="range" id="dur-sl" min="200" max="800" value="400" step="50"><span class="sv" id="dur-v">400ms</span></div>- <div class="lbl">Pause Between Words</div>- <div class="sr"><input type="range" id="pause-sl" min="500" max="4000" value="1500" step="100"><span class="sv" id="pause-v">1.5s</span></div>- <div class="lbl">Stagger Per Char</div>- <div class="sr"><input type="range" id="stag-sl" min="0" max="80" value="0" step="5"><span class="sv" id="stag-v">0ms</span></div>- <div class="lbl">Direction</div>- <select id="dir-sel">- <option value="up" selected>Up</option>- <option value="down">Down</option>- <option value="left">Left</option>- <option value="right">Right</option>- </select>- <div class="div"></div>- <div class="lbl">Words (one per line)</div>- <textarea id="words-inp">OCEAN+ <div class="hb-player">+ <button class="hb-play" type="button" id="btn-pause" data-hb-pause data-state="playing"><svg class="hb-ic hb-i-pause" viewBox="0 0 24 24" aria-hidden="true"><rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/></svg><svg class="hb-ic hb-i-play" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 3l14 9-14 9z"/></svg><span class="hb-pause-label">Pause</span></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 and see the difference as it moves.</p></div>+ </div>+ <div class="hb-settings">+ <div class="hb-setting">+ <p class="hb-setting-name" id="dir-lbl">Slide direction</p>+ <div class="seg" id="dir-seg" role="group" aria-labelledby="dir-lbl">+ <button type="button" data-dir="up" class="on" aria-pressed="true">Up</button>+ <button type="button" data-dir="down" aria-pressed="false">Down</button>+ <button type="button" data-dir="left" aria-pressed="false">Left</button>+ <button type="button" data-dir="right" aria-pressed="false">Right</button>+ </div>+ <p class="hb-hint">Which way the old letters leave and the new ones arrive.</p>+ </div>+ <div class="hb-setting">+ <p class="hb-setting-name" id="stag-lbl">Delay between letters</p>+ <div class="seg" id="stag-seg" role="group" aria-labelledby="stag-lbl">+ <button type="button" data-stag="0" class="on" aria-pressed="true">None</button>+ <button type="button" data-stag="30" aria-pressed="false">Short</button>+ <button type="button" data-stag="60" aria-pressed="false">Long</button>+ </div>+ <p class="hb-hint">A small delay sends the change across the word as a wave.</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-dur="650" aria-pressed="false">Slow</button>+ <button type="button" data-dur="400" class="on" aria-pressed="true">Normal</button>+ <button type="button" data-dur="250" aria-pressed="false">Fast</button>+ </div>+ <p class="hb-hint">How long each letter takes to slide.</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="hold-lbl">Time on each word</p>+ <div class="seg" id="hold-seg" role="group" aria-labelledby="hold-lbl">+ <button type="button" data-hold="900" aria-pressed="false">Short</button>+ <button type="button" data-hold="1500" class="on" aria-pressed="true">Medium</button>+ <button type="button" data-hold="2400" aria-pressed="false">Long</button>+ </div>+ <p class="hb-hint">How long each word stays still to be read.</p>+ </div>+ <div class="hb-setting">+ <label class="hb-setting-name" for="words-inp">Your words, one per line</label>+ <textarea class="hb-text" id="words-inp" autocomplete="off">OCEANRIVERSTORMLIGHTSOUND</textarea>- <button class="rst" id="restart-btn">↺ Restart</button>- <div class="kv"><span>Current word</span><span class="v" id="cur-word-kv">—</span></div>- </aside>-</div>+ <p class="hb-hint">Words of the same length morph most cleanly.</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 morph to [the word that should change, and the words it cycles through]. Split each word into letters. To change words, slide the current letters out of sight in one direction, then slide the next word's letters in from the opposite side; a small delay between letters, when the settings include one, sends the change across the word like a wave. Hold each word long enough to read, then morph to the next and repeat the list. Words of similar length look cleanest. Screen readers should hear each new word once, not its letters. If the visitor has reduced motion turned on, swap the words without movement. 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>Short labels</li><li>Status words</li><li>Hero headlines</li></ul>+ <h3>Avoid on</h3>+ <ul class="hb-tags hb-avoid"><li>Long words</li><li>Sentences</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>- let wordIdx=0,morphTimer=null,running=false;const wordEl=document.getElementById('current-word');- const dotsEl=document.getElementById('dots');- const curWordKv=document.getElementById('cur-word-kv');+ const stage=document.getElementById('stage');+ const vars=document.documentElement.style;+ const slowTog=document.getElementById('slow-tog');+ const wordsIn=document.getElementById('words-inp');+ let dir='up',morphDur=400,stag=0,hold=1500,wordIdx=0,morphTimer=null,morphing=false,paused=false;- function getWords(){- return document.getElementById('words-inp').value.split('\n').map(w=>w.trim().toUpperCase()).filter(Boolean);- }- function getDur(){return+document.getElementById('dur-sl').value}- function getPause(){return+document.getElementById('pause-sl').value}- function getStag(){return+document.getElementById('stag-sl').value}- function getDir(){return document.getElementById('dir-sel').value}+ function getWords(){return wordsIn.value.split('\n').map(w=>w.trim().toUpperCase()).filter(Boolean)}+ function curDur(){return slowTog.checked?morphDur*3:morphDur}+ function curStag(){return slowTog.checked?stag*3:stag}- function buildDots(words){- dotsEl.innerHTML='';- words.forEach((_,i)=>{- const d=document.createElement('div');d.className='cycle-dot'+(i===wordIdx?' active':'');- dotsEl.appendChild(d);- });- }- function updateDots(i){- dotsEl.querySelectorAll('.cycle-dot').forEach((d,j)=>d.classList.toggle('active',j===i));+ // The CSS formula is viewport-based; measure against the real stage width and shrink further if needed,+ // so a long typed word still fits instead of being cut off at the stage edge.+ function fit(){+ wordEl.style.fontSize='';+ const room=stage.clientWidth-64;+ if(wordEl.offsetWidth>room)wordEl.style.fontSize=Math.max(16,parseFloat(getComputedStyle(wordEl).fontSize)*room/wordEl.offsetWidth)+'px';}function showWord(word){wordEl.innerHTML='';word.split('').forEach((c,i)=>{- const s=document.createElement('span');s.className='morph-char';s.textContent=c;- const stag=getStag();+ const s=document.createElement('span');+ s.className='morph-char';+ s.textContent=c;if(stag>0)s.style.transitionDelay=(stag*i)+'ms';wordEl.appendChild(s);});+ fit();}- function morphTo(fromWord,toWord,done){- const dir=getDir();- const dur=getDur();- const stag=getStag();+ // Slides the current letters out, then builds the next word's letters off-screen and slides them in.+ // Slow motion stretches --morph-dur and the per-letter delay, so both waits below stretch with them;+ // the 60ms and 50ms parts stay the same either way.+ function morphTo(toWord,done){+ const d=curDur(),s=curStag();+ vars.setProperty('--morph-dur',d+'ms');const fromChars=[...wordEl.querySelectorAll('.morph-char')];const outClass='out-'+dir;-- // Exit current wordfromChars.forEach((c,i)=>{- if(stag>0)c.style.transitionDelay=(stag*i)+'ms';- else c.style.transitionDelay='0ms';+ c.style.transitionDelay=(s>0?s*i:0)+'ms';c.classList.add(outClass);});-- const exitDur=dur+(stag*(fromChars.length-1));+ const exitDur=d+(s*(fromChars.length-1));morphTimer=setTimeout(()=>{- // Build new word off-screenwordEl.innerHTML='';const enterDir={up:'enter-from-below',down:'enter-from-above',left:'enter-from-right',right:'enter-from-left'}[dir];const toChars=[];toWord.split('').forEach((c,i)=>{- const s=document.createElement('span');s.className='morph-char '+enterDir;- if(stag>0)s.style.transitionDelay=(stag*i)+'ms';- s.textContent=c;wordEl.appendChild(s);toChars.push(s);+ const s2=document.createElement('span');s2.className='morph-char '+enterDir;+ if(s>0)s2.style.transitionDelay=(s*i)+'ms';+ s2.textContent=c;wordEl.appendChild(s2);toChars.push(s2);});- // Animate in: force a style flush so the transition starts from the off-screen state+ fit();void wordEl.offsetWidth;toChars.forEach(c=>c.classList.remove(enterDir));- const enterDur=dur+(stag*(toChars.length-1));+ const enterDur=d+(s*(toChars.length-1));morphTimer=setTimeout(done,enterDur+50);},exitDur+60);}+ // Shows the current word, then (once Time on each word has passed) starts a morph to the next word.+ // The morph's own callback schedules the next cycle() after a short 100ms gap. The list repeats forever.function cycle(){- const words=getWords();- if(words.length<2){ // list edited down to one word mid-cycle: sync display, loop resumes on next edit- running=false;wordIdx=0;buildDots(words);- if(words[0]){showWord(words[0]);curWordKv.textContent=words[0]}else{wordEl.innerHTML='';curWordKv.textContent='—'}- return;- }- running=true;- if(wordIdx>=words.length)wordIdx=0; // word list was shortened mid-cycle- if(wordEl.textContent!==words[wordIdx])showWord(words[wordIdx]); // list edited mid-cycle: keep display, dots and readout in sync- if(dotsEl.children.length!==words.length)buildDots(words);- updateDots(wordIdx);- curWordKv.textContent=words[wordIdx];-+ const words=getWords();if(words.length<2)return;+ if(wordIdx>=words.length)wordIdx=0; // word list shortened mid-cyclemorphTimer=setTimeout(()=>{+ morphing=true;const next=(wordIdx+1)%words.length;- morphTo(words[wordIdx],words[next],()=>{+ morphTo(words[next],()=>{wordIdx=next;- updateDots(wordIdx);curWordKv.textContent=words[wordIdx];- morphTimer=setTimeout(cycle,100);+ morphing=false;+ if(!paused)morphTimer=setTimeout(cycle,100);});- },getPause());+ },hold);}function start(){- if(morphTimer)clearTimeout(morphTimer);running=false;wordIdx=0;+ clearTimeout(morphTimer);morphing=false;wordIdx=0;const words=getWords();- if(!words.length){wordEl.innerHTML='';dotsEl.innerHTML='';curWordKv.textContent='—';return}- buildDots(words);showWord(words[0]);curWordKv.textContent=words[0];- morphTimer=setTimeout(cycle,100);+ if(!words.length){wordEl.innerHTML='';return}+ showWord(words[0]);+ if(!paused)cycle();}- document.getElementById('restart-btn').addEventListener('click',start);- document.getElementById('words-inp').addEventListener('input',()=>{if(!running)start()});- document.getElementById('dur-sl').addEventListener('input',e=>{document.getElementById('dur-v').textContent=e.target.value+'ms';document.documentElement.style.setProperty('--morph-dur',e.target.value+'ms')});- document.getElementById('pause-sl').addEventListener('input',e=>{document.getElementById('pause-v').textContent=(e.target.value/1000).toFixed(1)+'s'});- document.getElementById('stag-sl').addEventListener('input',e=>{document.getElementById('stag-v').textContent=e.target.value+'ms'});+ // Registered at the top level, before the shared script (deferred) can run: under reduced motion it pauses+ // the loop on arrival, which this listener must catch. morphTimer holds whichever wait is current (the+ // hold, either half of a morph, or the 100ms gap), so clearing it always cancels the right thing. Pausing+ // mid-morph does nothing here — clearing morphTimer then would strand the letters out of sight — the morph+ // finishes on its own and its callback schedules nothing. Unpausing mid-morph also does nothing here; the+ // morph's callback will schedule the next step once it sees the loop is no longer paused.+ document.addEventListener('hb:pause',e=>{+ paused=e.detail.paused;+ if(paused){+ if(!morphing)clearTimeout(morphTimer);+ }else if(!morphing){+ clearTimeout(morphTimer);+ cycle();+ }+ });++ wordsIn.addEventListener('input',start);+ addEventListener('resize',fit);+ if(document.fonts)document.fonts.ready.then(fit); // the site font can still be loading when fit() first runs++ 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('dir-seg',d=>{dir=d.dir});+ choices('stag-seg',d=>{stag=+d.stag});+ choices('speed-seg',d=>{morphDur=+d.dur;vars.setProperty('--morph-dur',curDur()+'ms')});+ choices('hold-seg',d=>{hold=+d.hold});+ wordEl.setAttribute('aria-live','polite');+ vars.setProperty('--morph-dur',morphDur+'ms');start();</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.htmlindex b9de16e3..3c0c5771 100644--- a/index.html+++ b/index.html@@ -993,7 +993,7 @@ const CATS=[['variable-font-morph','Variable Font Morph','CSS font-variation-settings animates weight, slant, and casual axes of a variable font.'],['text-clip-path-reveal','Text Clip-Path Reveal','Each line of a headline is uncovered in turn. Best for big headlines.'],['marquee-ticker','Marquee / Ticker','Text scrolls sideways in an endless loop, with no seam. Best for news tickers.'],- ['text-morphing','Text Morphing','One word transitions into another character by character — each letter slides out as the next slides in.'],+ ['text-morphing','Text Morphing','One word changes into the next, letter by letter. Best for short labels.'],['text-gradient-animation','Text Gradient Animation','background-clip: text with animated background-position flows color through the characters.'],['outline-to-fill','Outline to Fill','Hollow letters fill with color, as a wipe or a fade. Best for big headlines.'],['enter-exit-typography','Enter/Exit Typography','Each phrase comes in, stays long enough to read, then leaves. Best for slogans.'],