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>Hamburger Menu Toggle — Animation Handbook</title>
<meta name="description" content="Three lines turn into an X as the menu opens. Best for mobile menus.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/hamburger-menu-toggle/">
<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="Hamburger Menu Toggle — Animation Handbook">
<meta property="og:description" content="Three lines turn into an X as the menu opens. Best for mobile menus.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/hamburger-menu-toggle/">
<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="Hamburger Menu Toggle — Animation Handbook">
<meta name="twitter:description" content="Three lines turn into an X as the menu opens. Best for mobile menus.">
<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": "Hamburger Menu Toggle", "name": "Hamburger Menu Toggle", "description": "Three lines turn into an X as the menu opens. Best for mobile menus.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/hamburger-menu-toggle/", "inLanguage": "en", "articleSection": "Micro-Interactions", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Micro-Interactions, Hamburger Menu Toggle"}</script>
<style>
:root{--ui-accent:#ff9d5c;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--dur:340ms;--ease:cubic-bezier(.65,0,.35,1);--bar-h:4px;--bar-w:44px}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
.stage{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:32px;background:#0b0b0d}
/* The button and the menu move as one pair. At rest the pair sits half the menu and its gap lower, so the button is in the middle of
the stage; opening the menu slides the pair back up, as the button rises when the menu grows. Transforms only. */
.pair{display:flex;flex-direction:column;align-items:center;gap:20px;width:100%;transform:translateY(calc(50% - 38px));transition:transform var(--dur) var(--ease)}
.pair:has(> .menu.show){transform:none}
/* The button */
.burger{position:relative;width:76px;height:76px;flex-shrink:0;display:grid;place-items:center;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:14px;font-family:inherit;cursor:pointer;-webkit-tap-highlight-color:transparent;touch-action:manipulation;transition:border-color var(--dur) var(--ease)}
.bars{position:relative;width:var(--bar-w);height:36px}
.bar{position:absolute;left:0;width:100%;height:var(--bar-h);border-radius:2px;background:var(--ui-accent);transition:transform var(--dur) var(--ease),opacity calc(var(--dur)*.6) var(--ease)}
.bar.top{top:0;transform-origin:center}
.bar.mid{top:50%;margin-top:calc(var(--bar-h)/-2)}
.bar.bot{bottom:0;transform-origin:center}
/* Open state: top+bottom rotate to cross, middle fades */
/* Travel = half the box height minus half a bar, so the arms meet at any thickness */
.burger[aria-expanded="true"] .bar.top{transform:translateY(calc(18px - var(--bar-h)/2)) rotate(45deg)}
.burger[aria-expanded="true"] .bar.mid{opacity:0;transform:scaleX(.2)}
.burger[aria-expanded="true"] .bar.bot{transform:translateY(calc(var(--bar-h)/2 - 18px)) rotate(-45deg)}
.burger[aria-expanded="true"]{border-color:var(--ui-accent)}
/* The menu keeps its full height in the layout and opens with opacity and transform; closed, it is also out of reach of Tab and screen readers */
.menu{flex-shrink:0;width:100%;max-width:280px;opacity:0;transform:translateY(-8px);visibility:hidden;transition:opacity var(--dur) var(--ease),transform var(--dur) var(--ease),visibility 0s linear var(--dur)}
.menu.show{opacity:1;transform:none;visibility:visible;transition:opacity var(--dur) var(--ease),transform var(--dur) var(--ease),visibility 0s}
.menu ul{list-style:none;display:flex;flex-direction:column;gap:6px}
.menu li{background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:6px;padding:12px 14px;font-size:12px;transform:translateY(-8px);opacity:0;transition:transform var(--dur) var(--ease),opacity var(--dur) var(--ease)}
.menu.show li{transform:translateY(0);opacity:1}
.menu.show li:nth-child(1){transition-delay:60ms}
.menu.show li:nth-child(2){transition-delay:110ms}
.menu.show li:nth-child(3){transition-delay:160ms}
.menu.show li:nth-child(4){transition-delay:210ms}
@media(hover:hover){.burger:hover{border-color:var(--ui-accent)}}
/* A window this short gives the stage 260px, less than the open button and menu need (278px): the gaps and the items give up some space so both fit */
@media(min-width:601px) and (max-height:640px){.pair{gap:12px}.menu ul{gap:4px}.menu li{padding:10px 14px}}
@media(prefers-reduced-motion:reduce){.bar,.menu,.menu li,.burger,.pair{transition:none!important}.menu li{transition-delay:0ms!important}}
/* See inside and Compare. Nothing here is drawn in Normal; every mode rule starts with the stage and its mode. */
.ghost,.caps,.twin,.sides,.menu .cap{display:none}
.cap{padding:3px 8px;border-radius:6px;background:rgba(11,11,13,.94);border:1px solid rgba(255,255,255,.16);color:#f4f4f2;font:600 12px/1.25 var(--hb-font);pointer-events:none}
.caps .cap{text-wrap:balance}
.twin,.twin *{transition:none!important}
/* The lines' box (44 by 36): where each line starts (dashed frames), where the outer two end (dotted X) and where they meet (dot) */
.ghost{position:absolute;inset:0;pointer-events:none}
.ghost i{position:absolute;left:-3px;right:-3px;height:calc(var(--bar-h) + 4px);border-radius:4px}
.ghost .gt,.ghost .gm,.ghost .gb{border:1px dashed rgba(255,255,255,.6)}
.ghost .gt{top:-2px}
.ghost .gm{top:calc(50% - var(--bar-h)/2 - 2px)}
.ghost .gb{bottom:-2px}
.ghost .gx{top:calc(50% - var(--bar-h)/2 - 2px);border:1px dotted #fff}
.ghost .ga{transform:rotate(45deg)}
.ghost .gc{transform:rotate(-45deg)}
.ghost .gdot{left:50%;top:50%;right:auto;width:6px;height:6px;margin:-3px 0 0 -3px;border-radius:50%;background:#fff;box-shadow:0 0 0 1.5px #111114}
/* See inside: captions, the button drawn twice as big and the menu in one row, none of it sliding */
.stage[data-hb-mode="inside"]{--zoom:2;display:grid;grid-template-columns:minmax(130px,210px) calc(76px * var(--zoom)) minmax(150px,280px);justify-content:center;align-content:center;align-items:center;column-gap:clamp(12px,3vw,28px);padding:10px 12px}
@media(min-width:761px) and (min-height:761px){.stage[data-hb-mode="inside"]{--zoom:2.6}}
.stage[data-hb-mode="inside"] .pair:not(.twin){display:contents}
.stage[data-hb-mode="inside"] .caps{display:flex;flex-direction:column;align-items:flex-start;gap:6px;grid-area:1/1}
.stage[data-hb-mode="inside"] .burger{grid-area:1/2;justify-self:center;transform:scale(var(--zoom))}
.stage[data-hb-mode="inside"] .menu{grid-area:1/3;position:relative}
.stage[data-hb-mode="inside"] .ghost{display:block}
@media(min-width:1025px){.stage[data-hb-mode="inside"] .menu .cap{display:block;position:absolute;right:0;bottom:calc(100% + 6px);white-space:nowrap}}
/* Compare: two whole pairs, the plain swap first. Short spacing so the names fit above the open pair. */
.stage[data-hb-mode="compare"]{position:relative;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-items:center;padding:0}
.stage[data-hb-mode="compare"]::after{content:"";position:absolute;left:50%;top:8%;bottom:8%;width:1px;background:rgba(255,255,255,.14)}
.stage[data-hb-mode="compare"] .twin{display:flex}
.stage[data-hb-mode="compare"] .pair{padding:0 8px;gap:12px}
.stage[data-hb-mode="compare"] .menu ul{gap:4px}
.stage[data-hb-mode="compare"] .menu li{padding:10px 14px}
.stage[data-hb-mode="compare"] .sides{display:grid;grid-template-columns:1fr 1fr;justify-items:center;position:absolute;left:0;right:0;top:4px;z-index:2}
.stage[data-hb-mode="compare"] .sides .cap{white-space:nowrap}
/* The held moment: the real half part way through, with a faint ghost of where its lines started */
.stage[data-hb-mode="compare"].posed .pair:not(.twin),.stage[data-hb-mode="compare"].posed .pair:not(.twin) *{transition:none!important}
.stage[data-hb-mode="compare"].posed .ghost{display:block}
.stage[data-hb-mode="compare"] .ghost i:not(.gt):not(.gm):not(.gb){display:none}
@media(min-width:601px) and (max-height:629px){.stage[data-hb-mode="compare"] .sides .cap{justify-self:start;margin-left:calc(50% + 46px)}}
/* Springy lifts the button about 8px above its open place for a moment: the list sits a little shorter so that stays inside the box and below the names */
@media(min-width:601px) and (max-height:650px){.stage[data-hb-mode="compare"] .menu li{padding:7px 14px}}
@media(max-width:600px){
.stage[data-hb-mode="inside"]{--zoom:1.5;grid-template-columns:114px minmax(0,1fr);grid-template-rows:auto auto 114px auto auto;row-gap:3px;column-gap:12px;padding:6px 10px}
.stage[data-hb-mode="inside"] .caps{display:contents}
.stage[data-hb-mode="inside"] .cap-a{grid-area:1/1/2/3;justify-self:start}
.stage[data-hb-mode="inside"] .cap-c{grid-area:2/1;align-self:end;justify-self:start}
.stage[data-hb-mode="inside"] .burger{grid-area:3/1}
.stage[data-hb-mode="inside"] .cap-d{grid-area:4/1;align-self:start;justify-self:start}
.stage[data-hb-mode="inside"] .cap-t{grid-area:5/1/6/3;align-self:end;justify-self:start}
.stage[data-hb-mode="inside"] .menu{grid-area:2/2/5/3;align-self:center}
.stage[data-hb-mode="inside"] .menu ul{gap:4px}
.stage[data-hb-mode="inside"] .menu li{padding:10px 14px}
.stage[data-hb-mode="compare"] .pair{gap:10px}
.stage[data-hb-mode="compare"] .menu li{padding:7px 14px}
}
</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="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="../swipe-to-dismiss/" rel="prev" aria-label="Previous: Swipe to Dismiss"><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>Swipe to Dismiss</span></a><a href="../theme-toggle-morph/" rel="next" aria-label="Next: Theme Toggle Morph"><span><span class="hb-dir">Next: </span>Theme Toggle Morph</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">04.23 · Micro-Interactions</p>
<h1>Hamburger Menu Toggle</h1>
<p class="hb-lede">Three lines turn into an X as the menu opens. Best for mobile menus.</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>Press the button to open the menu and again to close it, or press Show me.</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">
<div class="caps" aria-hidden="true">
<span class="cap cap-a" data-hb-caption>Top and bottom lines slide to the middle and turn</span>
<span class="cap cap-c" data-hb-caption>The middle line fades away</span>
<span class="cap cap-d" data-hb-caption>They meet at the center as an X</span>
<span class="cap cap-t" data-hb-caption>Takes about a third of a second, easing in and out</span>
</div>
<div class="pair">
<button type="button" class="burger" id="burger" aria-label="Open menu" aria-expanded="false" aria-controls="menu">
<span class="bars" aria-hidden="true">
<span class="bar top"></span>
<span class="bar mid"></span>
<span class="bar bot"></span>
<span class="ghost"><i class="gt"></i><i class="gm"></i><i class="gb"></i><i class="gx ga"></i><i class="gx gc"></i><i class="gdot"></i></span>
</span>
</button>
<nav class="menu" id="menu" aria-label="Demo menu">
<ul>
<li>Home</li>
<li>Work</li>
<li>About</li>
<li>Contact</li>
</ul>
<span class="cap cap-i" data-hb-caption aria-hidden="true">Items arrive one after another</span>
</nav>
</div>
<div class="sides" aria-hidden="true"><span class="cap" data-hb-caption>Swaps at once</span><span class="cap" data-hb-caption>Becomes an X</span></div>
</div>
<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>
<label class="hb-toggle"><input class="hb-switch" type="checkbox" role="switch" id="slow-tog" data-hb-slowmo="css" autocomplete="off"><span>Slow motion</span></label>
</div>
<div class="hb-mode-notes" aria-live="polite">
<p data-hb-for="inside" hidden>Inside, the dotted X is where the lines end: the top and bottom lines slide to the middle and turn to cross, and the middle one fades. Press the button, or Show me.</p>
<p data-hb-for="compare" hidden>Swaps at once: the icon and menu simply change; Becomes an X: the same three lines move into an X and the items arrive one by one. Press the button, or Show me.</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, 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="speed-lbl">Speed</p>
<div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
<button type="button" data-ms="550" aria-pressed="false">Slow</button>
<button type="button" data-ms="340" class="on" aria-pressed="true">Normal</button>
<button type="button" data-ms="200" aria-pressed="false">Fast</button>
</div>
<p class="hb-hint">How long the lines take to turn into an X.</p>
</div>
<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="cubic-bezier(.65,0,.35,1)" class="on" aria-pressed="true">Gentle</button>
<button type="button" data-ease="cubic-bezier(.34,1.56,.64,1)" aria-pressed="false">Springy</button>
<button type="button" data-ease="ease-out" aria-pressed="false">Smooth</button>
<button type="button" data-ease="linear" aria-pressed="false">Even</button>
</div>
<p class="hb-hint">Springy lets the X overshoot a little, then settle.</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="thick-lbl">Line thickness</p>
<div class="seg" id="thick-seg" role="group" aria-labelledby="thick-lbl">
<button type="button" data-px="2" aria-pressed="false">Thin</button>
<button type="button" data-px="4" class="on" aria-pressed="true">Medium</button>
<button type="button" data-px="6" aria-pressed="false">Thick</button>
</div>
<p class="hb-hint">Thicker lines read better at small sizes.</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 menu button whose three lines turn into an X to [the menu button in your header]. When it is pressed, the top and bottom lines move to the middle and turn to cross each other while the middle line fades away, and pressing it again reverses the change. Use the same three lines for both states, moving and turning them rather than swapping icons, and move each outer line exactly to the middle so the X meets at its center. Make it a real button that tells screen readers whether the menu is open. If the visitor has reduced motion turned on, switch between the two icons 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>
<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>Mobile menus</li><li>Compact headers</li><li>Side panels</li></ul>
<h3>Avoid on</h3>
<ul class="hb-tags hb-avoid"><li>Wide desktop menus</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 stage=document.querySelector('.stage');
const btn=document.getElementById('burger');
const menu=document.getElementById('menu');
const slowTog=document.getElementById('slow-tog');
const vars=document.documentElement.style;
// Everything on the stage that moves, so a run can start from rest without animating
const moving=[...stage.querySelectorAll('.pair,.burger,.bar,.menu,.menu li')];
const pair=stage.querySelector('.pair');
const motionOk=!matchMedia('(prefers-reduced-motion:reduce)').matches;
let dur=340,ease='cubic-bezier(.65,0,.35,1)',runTimers=[],mode='normal',kept=null;
// Compare's first half: a copy of the button and menu that swaps at once. Made once, after `moving` is collected: no ids,
// out of the Tab order and hidden from screen readers. setOpen() sets it as it sets the real one.
const twin=document.createElement('div');
twin.className='pair twin';twin.inert=true;twin.setAttribute('aria-hidden','true');
twin.innerHTML='<span class="burger" aria-expanded="false"><span class="bars"><span class="bar top"></span><span class="bar mid"></span><span class="bar bot"></span></span></span><div class="menu"><ul>'+[...menu.querySelectorAll('li')].map(li=>'<li>'+li.textContent+'</li>').join('')+'</ul></div>';
stage.insertBefore(twin,pair);
const twinBtn=twin.querySelector('.burger'),twinMenu=twin.querySelector('.menu');
function twinSet(on){twinBtn.setAttribute('aria-expanded',String(on));twinMenu.classList.toggle('show',on)}
// The button and Show me both open and close the menu through toggle(). A press also lifts Compare's held moment, in the same
// step, so the lines carry on from where the moment held them.
function isOpen(){return btn.getAttribute('aria-expanded')==='true'}
function setOpen(on){
unpose();
btn.setAttribute('aria-expanded',String(on));
btn.setAttribute('aria-label',on?'Close menu':'Open menu');
menu.classList.toggle('show',on);
twinSet(on);
}
function toggle(){setOpen(!isOpen())}
btn.addEventListener('click',toggle);
// Show me: one run at a time. Every timer of the run goes through later(); stopRun() cancels the whole run.
// later(fn, move, hold) waits move*(slow?3:1) + hold ms: Slow motion triples the movement, never the hold.
function later(fn,move,hold){
const id=setTimeout(()=>{runTimers=runTimers.filter(t=>t!==id);fn()},move*(slowTog.checked?3:1)+(hold||0));
runTimers.push(id);
}
function running(){return runTimers.length>0}
function stopRun(){runTimers.forEach(clearTimeout);runTimers=[]}
// A run starts with the menu closed, put there without animating: the transitions are turned off, the menu is closed,
// a reflow makes it stick, and the transitions come back.
function toRest(on){
moving.forEach(el=>el.style.setProperty('transition','none','important'));
setOpen(!!on);
void stage.offsetWidth;
moving.forEach(el=>el.style.removeProperty('transition'));
}
// The menu opens as a press opens it, and closes once the lines and the last item (which starts 210ms late) have arrived and 1200ms have passed.
document.getElementById('btn-demo').addEventListener('click',()=>{
stopRun();
toRest();
toggle();
later(()=>{toggle();later(refresh,dur,700)},dur+210,1200);
});
// The visitor pressed, typed, scrolled or touched inside the stage: the run stops and the menu stays as it is.
document.addEventListener('hb:input',()=>{if(running())stopRun()});
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('speed-seg',d=>{dur=+d.ms;vars.setProperty('--dur',dur+'ms');refresh()});
choices('feel-seg',d=>{ease=d.ease;vars.setProperty('--ease',ease);refresh()});
choices('thick-seg',d=>{vars.setProperty('--bar-h',d.px+'px');refresh()});
slowTog.addEventListener('change',words);
// ---- See inside and Compare
const EASES={'ease-out':[0,0,.58,1],linear:[0,0,1,1]};
const FEEL={'cubic-bezier(.65,0,.35,1)':'easing in and out','cubic-bezier(.34,1.56,.64,1)':'overshooting a little','ease-out':'slowing to a stop',linear:'at one steady speed'};
const DELAYS=[60,110,160,210];
const HELD=.6;
const tCap=stage.querySelector('.cap-t');
const noteIn=document.querySelector('[data-hb-for="inside"]'),noteCmp=document.querySelector('[data-hb-for="compare"]');
const RM_CMP_HELD='Shown still, half way through: Swaps at once already shows the X and the whole menu; Becomes an X is part way, its items still arriving.';
const RM_CMP_PLAIN='With motion off, Becomes an X swaps at once too, so the halves match. Press Compare again to see the still half way through.';
if(!motionOk)noteCmp.textContent=RM_CMP_HELD;
if(!motionOk)noteIn.textContent='Inside, shown still: the dotted X is where the lines end; with motion on, the top and bottom lines slide to the middle and turn to cross, and the middle one fades.';
// The height of a speed curve at a share x of its time: the curve's own t for x found by halving, then its height there
function curveAt(spec,x){
const [a,b,c,e]=EASES[spec]||spec.match(/-?[\d.]+/g).map(Number);
const at=(p,q,t)=>3*p*t*(1-t)*(1-t)+3*q*t*t*(1-t)+t*t*t;
let lo=0,hi=1,t=x;
for(let i=0;i<30;i++){t=(lo+hi)/2;if(at(a,c,t)<x)lo=t;else hi=t}
return at(b,e,t);
}
// The caption about time, in words, for the Speed and Feel chosen (three times as long in Slow motion)
function words(){
const ms=dur*(slowTog.checked?3:1);
const t=ms<=250?'a fifth of a second':ms<=420?'about a third of a second':ms<=700?'over half a second':ms<=1200?'about a second':'nearly two seconds';
const text='Takes '+t+', '+FEEL[ease];
if(tCap.textContent!==text)tCap.textContent=text;
}
function note(){
if(motionOk)return;
const text=stage.classList.contains('posed')?RM_CMP_HELD:RM_CMP_PLAIN;
if(noteCmp.textContent!==text)noteCmp.textContent=text;
}
// Compare's held moment: the real half half way through the change after a press, worked out with the page's own time, curve
// and delays, on top of a menu that is still closed. Inline values with the transitions off; a press lifts them (setOpen).
const put=(el,css)=>Object.assign(el.style,css);
const clamp=v=>Math.min(Math.max(v,0),1);
function pose(){
const half=dur*HELD,p=curveAt(ease,HELD),[top,mid,bot]=btn.querySelectorAll('.bar');
stage.classList.add('posed');twinSet(true);
menu.setAttribute('aria-hidden','true');
put(pair,{transform:`translateY(calc((50% - 38px) * ${1-clamp(p)}))`});
put(btn,{borderColor:`color-mix(in srgb,var(--ui-accent) ${100*clamp(p)}%,var(--ui-border))`});
put(top,{transform:`translateY(calc((18px - var(--bar-h) / 2) * ${p})) rotate(${45*p}deg)`});
put(bot,{transform:`translateY(calc((var(--bar-h) / 2 - 18px) * ${p})) rotate(${-45*p}deg)`});
put(mid,{opacity:1-clamp(curveAt(ease,Math.min(1,HELD/.6))),transform:`scaleX(${1-.8*p})`});
put(menu,{opacity:clamp(p),transform:`translateY(${-8*(1-p)}px)`,visibility:'visible'});
menu.querySelectorAll('li').forEach((li,i)=>{
const q=half>DELAYS[i]?curveAt(ease,(half-DELAYS[i])/dur):0;
put(li,{opacity:clamp(q),transform:`translateY(${-8*(1-q)}px)`});
});
note();
}
// Takes the held moment away: with `snap` the closed look comes back at once, otherwise the next change starts from it
function unpose(snap){
if(!stage.classList.contains('posed'))return;
moving.forEach(el=>{['transform','opacity','visibility','borderColor'].forEach(k=>{el.style[k]=''})});
if(snap)void stage.offsetWidth;
stage.classList.remove('posed');
menu.removeAttribute('aria-hidden');
twinSet(isOpen());
note();
}
// Draws the mode for the state the page is in: the held moment shows in Compare while the menu is closed and no run is pending
// (it does not come back by itself after the visitor's own press: it comes back with a mode press, a setting or Show me)
function refresh(){
words();
if(mode==='compare'&&!isOpen()&&!running())pose();
else unpose(mode!=='compare');
}
// Normal's own state (open or closed) is kept while a mode shows and put back when Normal is pressed
document.addEventListener('hb:mode',e=>{
const was=mode;mode=e.detail.mode;
if(mode==='normal'){if(kept){stopRun();toRest(kept.open);kept=null}}
else if(was==='normal')kept={open:isOpen()&&!running()};
if(mode==='compare'&&isOpen()&&!running())toRest(false);
refresh();
});
words();
</script>
</body>
</html>