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.

33.1 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Hide-on-Scroll Header — Animation Handbook</title>
  <meta name="description" content="Scrolling down hides the top bar; scrolling up shows it. Best for mobile pages.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/hide-on-scroll-header/">
  <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="Hide-on-Scroll Header — Animation Handbook">
  <meta property="og:description" content="Scrolling down hides the top bar; scrolling up shows it. Best for mobile pages.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/hide-on-scroll-header/">
  <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="Hide-on-Scroll Header — Animation Handbook">
  <meta name="twitter:description" content="Scrolling down hides the top bar; scrolling up shows it. Best for mobile pages.">
  <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": "Hide-on-Scroll Header", "name": "Hide-on-Scroll Header", "description": "Scrolling down hides the top bar; scrolling up shows it. Best for mobile pages.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/hide-on-scroll-header/", "inLanguage": "en", "articleSection": "Scroll-Based", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Scroll-Based, Hide-on-Scroll Header"}</script>
  <style>
    :root{--ui-accent:#6ea8ff;--bar-h:56px;--dur:300ms;--ease:cubic-bezier(.2,.7,.3,1)}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;overflow:hidden;background:#0b0b0d}
    /* The bar floats over the page and only ever moves with a transform; the page under it is what scrolls */
    .topbar{position:absolute;top:0;left:0;right:0;z-index:2;height:var(--bar-h);display:flex;align-items:center;justify-content:space-between;gap:12px;
      padding:0 clamp(14px,3vw,24px);background:#171920;border-bottom:1px solid rgba(255,255,255,.1);
      transition:transform var(--dur) var(--ease),opacity var(--dur) var(--ease);will-change:transform}
    .brand,.nav,.menu{display:flex;align-items:center;transition:transform var(--dur) var(--ease)}
    .brand{gap:10px;transform-origin:left center;font-weight:700;font-size:17px;letter-spacing:-.01em;color:#f4f4f2;white-space:nowrap}
    .logo{width:22px;height:22px;border-radius:50%;background:var(--ui-accent);flex:none}
    .nav{gap:clamp(14px,2.4vw,24px);transform-origin:right center;font-size:14px;color:#adadb2}
    .menu{display:none;flex-direction:column;align-items:stretch;justify-content:center;gap:4px;width:20px;transform-origin:right center}
    .menu i{display:block;height:2px;border-radius:1px;background:#d6d6da}
    /* Scrolled down: the bar slides up by its own height (border included) and 2px to spare, out of view */
    .topbar.away{transform:translateY(calc(-100% - 2px))}
    /* Shrinks instead: a slim strip stays, its contents smaller and centered in what is left of it */
    .stage.shrink .topbar.away{transform:translateY(-18px)}
    .stage.shrink .topbar.away .brand{transform:translateY(9px) scale(.82)}
    .stage.shrink .topbar.away .nav,.stage.shrink .topbar.away .menu{transform:translateY(9px) scale(.9)}
    .snap,.snap *{transition:none!important}
    .scroller{position:absolute;inset:0;overflow-y:auto;scrollbar-width:none;padding-top:var(--bar-h)}
    .scroller::-webkit-scrollbar{display:none}
    .post{max-width:640px;margin:0 auto;padding:clamp(22px,4vw,40px) clamp(16px,4vw,32px) 40px}
    .kicker{font-size:13px;font-weight:600;letter-spacing:.08em;text-transform:uppercase;color:var(--ui-accent)}
    .post h3{margin:10px 0 12px;font-weight:800;font-size:clamp(24px,3.6vw,34px);line-height:1.15;letter-spacing:-.02em;color:#f4f4f2}
    .post h4{margin:30px 0 8px;font-weight:700;font-size:clamp(18px,2.4vw,21px);color:#f4f4f2}
    .post p{font-size:15px;line-height:1.7;color:#adadb2}
    .post .lead{font-size:17px;color:#d6d6da}
    .pic{margin-top:26px;aspect-ratio:16/7;border-radius:10px;background:linear-gradient(135deg,#1f3a66,#3d2a5c 55%,#5a2d45)}
    .pic.two{background:linear-gradient(135deg,#123d3a,#1f3a66 60%,#2b2f45)}
    .post .end{margin-top:30px;padding-top:18px;border-top:1px solid rgba(255,255,255,.09);color:#8a8a92}
    /* See inside and Compare draw in layers of the stage, outside the scroller, that ignore the pointer and the keyboard */
    .fx,.fx-in,.fx-cmp,.home{display:none;position:absolute;pointer-events:none}
    .fx,.fx-in,.fx-cmp{inset:0}
    .fx{z-index:6;overflow:hidden}
    .stage[data-hb-mode="inside"] .fx,.stage[data-hb-mode="compare"] .fx,.stage[data-hb-mode="inside"] .home,.stage[data-hb-mode="compare"] .fx-cmp{display:block}
    .stage[data-hb-mode="inside"] .fx-in{display:flex}
    .cap{max-width:100%;padding:3px 8px;border-radius:10px;overflow-wrap:anywhere;text-wrap:balance;background:rgba(11,11,13,.95);color:#f4f4f2;
      border:1px solid rgba(244,244,242,.6);font:600 13px/1.3 var(--hb-font)}
    /* See inside: a track for the whole scroll (its top zone shaded, a marker at the current place, an arrow for the last move
       that counted) and the bar's home drawn as a dashed outline under the bar. Only the text is dimmed. */
    .stage[data-hb-mode="inside"] .post{opacity:.4}
    .home{top:0;left:0;right:0;height:var(--bar-h);z-index:1;border:2px dashed rgba(244,244,242,.85);background:rgba(11,11,13,.7)}
    .fx-in{flex-direction:column;padding:calc(var(--bar-h) + 8px) 8px 8px}
    .mid{position:relative;flex:1;min-height:0}
    .lbls{position:absolute;left:0;right:58px;top:0;bottom:0}
    .cap-zone,.cap-mv{position:absolute;right:0}
    .cap-mv{top:50%;translate:0 -50%;display:flex;gap:6px;align-items:center;border-style:solid}
    .car,.ca{fill:none;stroke:var(--ui-accent);stroke-width:2.4;stroke-linecap:round;stroke-linejoin:round}
    .car{flex:none;width:14px;height:14px}
    .fx-in[data-dir="up"] .car,.fx-in[data-dir="up"] .mka{rotate:180deg}
    .fx-in[data-dir="none"] .cap-mv{border-style:dashed}
    .fx-in[data-dir="none"] .car{opacity:.55}
    .trk{position:absolute;right:0;top:0;bottom:0;width:10px;background:#20222b;border:1px solid rgba(244,244,242,.6)}
    .zone{position:absolute;left:0;right:0;top:0;background:var(--ui-accent)}
    .mk{position:absolute;left:-7px;right:-7px;top:0;height:0}
    .mk::before{content:"";position:absolute;left:0;right:0;top:-2px;height:4px;background:#fff;box-shadow:0 0 0 1.5px #0b0b0d}
    .mka{display:none;position:absolute;right:100%;margin-right:5px;top:-11px;width:22px;height:22px}
    .fx-in:not([data-dir="none"]) .mka{display:block}
    .cap-bot{align-self:flex-start;margin-top:8px}
    /* Compare: the page twice, stacked, each half the box's width and half its height. The top half is a copy that follows the
       real scroll under a bar that never moves. The real box keeps its full size and only sits half a box lower, its lower half
       cut off by the stage, so its top half fills the lower half of the stage. The real bar slides up under the top half. */
    .stage[data-hb-mode="compare"]{overflow:clip}
    .stage[data-hb-mode="compare"] .scroller{inset:auto;left:0;right:0;top:calc(50% + 1px);height:100%;scroll-margin-bottom:var(--sm,0px)} /* focus must not scroll the window to the half below the stage */
    .stage[data-hb-mode="compare"]>.topbar{top:calc(50% + 1px)}
    .stage[data-hb-mode="compare"] .scroller:focus-visible{outline:none}
    .stage[data-hb-mode="compare"] .scroller:focus-visible~.fx::after{content:"";position:absolute;left:0;right:0;top:calc(50% + 1px);bottom:0;outline:2px solid var(--hb-accent,var(--ui-accent));outline-offset:-3px}
    .h1{position:absolute;top:0;left:0;right:0;height:calc(50% - 1px);overflow:hidden;background:#0b0b0d}
    .cpage{position:absolute;left:0;right:0;top:0;padding-top:var(--bar-h);will-change:transform}
    .h1 .topbar{transition:none}
    .split{position:absolute;left:0;right:0;top:calc(50% - 1px);height:2px;background:#8a8a92}
    .row{position:absolute;left:8px;right:8px;display:flex;flex-wrap:wrap;gap:6px;align-items:flex-start}
    .r1{top:calc(var(--bar-h) + 6px)}
    .r2{top:calc(50% + 7px + var(--bar-h))}
    .cap-rules{position:absolute;left:8px;bottom:8px}
    /* the real bar at rest, posed half way through leaving (only in Compare, so the halves differ while the bar is showing) */
    .stage[data-hb-mode="compare"] .topbar.posed{transform:translateY(calc(-50% - 1px))}
    .stage[data-hb-mode="compare"].shrink .topbar.posed{transform:translateY(-9px)}
    .stage[data-hb-mode="compare"].shrink .topbar.posed .brand{transform:translateY(4.5px) scale(.91)}
    .stage[data-hb-mode="compare"].shrink .topbar.posed .nav,.stage[data-hb-mode="compare"].shrink .topbar.posed .menu{transform:translateY(4.5px) scale(.95)}
    @media(max-width:600px){:root{--bar-h:52px}.nav{display:none}.menu{display:flex}}
    /* Reduced motion: the bar fades out and back instead of sliding, and the slim strip appears without moving */
    @media(prefers-reduced-motion:reduce){
      .topbar{transition:opacity var(--dur) linear;will-change:auto}
      .brand,.nav,.menu{transition:none}
      .topbar.away{transform:none;opacity:0}
      .stage.shrink .topbar.away{transform:translateY(-18px);opacity:1}
      .stage[data-hb-mode="compare"] .topbar.posed{transform:none;opacity:.5}
      .stage[data-hb-mode="compare"].shrink .topbar.posed{transform:translateY(-18px);opacity:1}
      .stage[data-hb-mode="compare"].shrink .topbar.posed .brand{transform:translateY(9px) scale(.82)}
      .stage[data-hb-mode="compare"].shrink .topbar.posed .nav,.stage[data-hb-mode="compare"].shrink .topbar.posed .menu{transform:translateY(9px) scale(.9)}
    }
  </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="../scroll-background-color/" rel="prev" aria-label="Previous: Scroll-Driven Background Color"><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>Scroll-Driven Background Color</span></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">01.27 · Scroll-Based</p>
    <h1>Hide-on-Scroll Header</h1>
    <p class="hb-lede">Scrolling down hides the top bar; scrolling up shows it. Best for mobile pages.</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">Scroll it</h2><p>Scroll down inside the box, then back up, 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" id="stage">
      <div class="topbar" id="topbar" aria-hidden="true">
        <span class="brand"><span class="logo"></span>Field Notes</span>
        <span class="nav"><span>Latest</span><span>Topics</span><span>About</span></span>
        <span class="menu"><i></i><i></i><i></i></span>
      </div>
      <div class="scroller" id="scroller" tabindex="0" role="region" aria-label="A page whose top bar slides away as you scroll down">
        <article class="post">
          <p class="kicker">Field Notes · Design</p>
          <h3>A bar that steps aside while you read</h3>
          <p class="lead">Scroll down and the bar above slides out of the way. Scroll back up to bring it home.</p>
          <div class="pic" aria-hidden="true"></div>
          <h4>Scroll down</h4>
          <p>Reading down the page, you do not need the menu, so the bar slides up out of view and the story gets the whole screen.</p>
          <h4>Scroll back up</h4>
          <p>The bar returns: at the first move up, or only once you are back near the top, whichever the page asks for.</p>
          <div class="pic two" aria-hidden="true"></div>
          <h4>Near the top it stays</h4>
          <p>Close to the top of the page the bar always shows, whichever way you scroll.</p>
          <h4>Small moves do not count</h4>
          <p>A few pixels of jitter never flip the bar in and out, so it does not flicker.</p>
          <h4>It floats over the page</h4>
          <p>The bar sits on top of the page and moves with a transform, so nothing below it jumps.</p>
          <p class="end">The end of the page. Scroll back up.</p>
        </article>
      </div>
      <div class="home" inert aria-hidden="true"></div>
      <div class="fx" inert aria-hidden="true">
        <div class="fx-in" data-dir="none">
          <div class="mid">
            <div class="lbls">
              <p class="cap cap-zone" data-hb-caption>Top zone: the bar always shows</p>
              <p class="cap cap-mv" data-hb-caption><svg class="car" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M6 13l6 6 6-6"/></svg><span>Example: a move down hides it</span></p>
            </div>
            <div class="trk"><i class="zone"></i><div class="mk"><svg class="mka" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="11" fill="#0b0b0d" stroke="rgba(244,244,242,.6)" stroke-width="1.5"/><path class="ca" d="M12 7v10M8 13l4 4 4-4"/></svg></div></div>
          </div>
          <p class="cap cap-bot" data-hb-caption>Moves of a few pixels do not count; it slides in about a third of a second</p>
        </div>
        <div class="fx-cmp">
          <div class="h1"><div class="cpage"></div></div>
          <i class="split"></i>
          <div class="row r1"><p class="cap" data-hb-caption>Always there</p></div>
          <div class="row r2"><p class="cap cap-n2" data-hb-caption>Hides on scroll</p><p class="cap cap-pose" data-hb-caption hidden>Half way hidden</p></div>
          <p class="cap cap-rules" data-hb-caption>Takes about a third of a second; back on any scroll up</p>
        </div>
      </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>
      <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>
    <div class="hb-mode-notes" aria-live="polite">
      <p data-hb-for="inside" hidden>Inside, the track is the page top to bottom: in its shaded top zone the bar always shows; the arrow is the last move that counted. Scroll down and up, or press Show me.</p>
      <p data-hb-for="compare" hidden>Always there keeps the bar, so less of the page shows; Hides on scroll slides it away as you scroll down, shown half way at rest. Scroll down and up, or press 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 scroll 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="700" aria-pressed="false">Slow</button>
          <button type="button" data-ms="300" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-ms="150" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">How quickly the bar slides away and back.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="back-lbl">Comes back</p>
        <div class="seg" id="back-seg" role="group" aria-labelledby="back-lbl">
          <button type="button" data-back="any" class="on" aria-pressed="true">On any scroll up</button>
          <button type="button" data-back="top" aria-pressed="false">Only near the top</button>
        </div>
        <p class="hb-hint">Any scroll up keeps the menu one small move away.</p>
      </div>
      <div class="hb-setting">
        <label class="hb-switch-row"><span>Shrinks instead of hiding</span><input class="hb-switch" type="checkbox" role="switch" id="shrink-tog" autocomplete="off"></label>
        <p class="hb-hint">A slim bar stays in view instead of leaving.</p>
      </div>
    </div>
  </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 hide-on-scroll header to [the top bar of your site]. When the visitor scrolls down, slide the bar up out of view, or shrink it to a slim strip if the settings ask for that; when they scroll back up, bring it back as the settings say. Tell the direction by comparing each scroll position with the last one, ignore moves of a few pixels so the bar never flickers, and always show it near the top of the page. Let the bar float over the content, move it only with a transform and read the scroll once per frame. Touch scrolling counts too. If the visitor has reduced motion turned on, fade the bar out and in instead. 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 pages</li><li>News and blogs</li><li>Long articles</li><li>Online shops</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Short pages</li><li>Bars with key buttons</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.getElementById('stage'),scroller=document.getElementById('scroller'),bar=document.getElementById('topbar');
  const slowTog=document.getElementById('slow-tog'),shrinkTog=document.getElementById('shrink-tog');
  const motionMQ=window.matchMedia('(prefers-reduced-motion: reduce)');
  const vars=document.documentElement.style;
  const JITTER=6,MOVE=1100,HOLD=500; // a move under JITTER px is ignored; a Show me glide takes MOVE ms each way
  let ms=300,comeBack='any',maxY=0,nearTop=112,lastY=0,away=false,ticking=false;
  let runFrame=0,runTimers=[],runFrom=0;
let mode='normal',dir=null,trackH=0,posed=false,posedAt=0,poseTimer=0,seenY=0; // dir: the last move that counted ('down', 'up' or none yet)
const POSE=500; // Compare: how long the box rests before the bar is posed half way again

// See inside and Compare: the listener sits here, at the top level; what it draws is defined below
document.addEventListener('hb:mode',e=>{
  mode=e.detail.mode;
  scroller.setAttribute('aria-label',label());
  clearTimeout(poseTimer);setPose(false,true);
  words();measure();
  if(mode==='compare')running()?schedulePose():setPose(!away,true);
});

  // The visitor pressed, typed, scrolled or touched inside the stage: a Show me run under way stops where it is.
  document.addEventListener('hb:input',()=>{if(running())stopRun()});

  // Layout is read here, never in the scroll handler: at the start, after the site font loads and on resize.
  function measure(){maxY=Math.max(0,scroller.scrollHeight-scroller.clientHeight);nearTop=bar.offsetHeight*2;scroller.style.setProperty('--sm',-(scroller.clientHeight/2+2)+'px');fit()}
  function setAway(on){if(on===away)return;away=on;bar.classList.toggle('away',on);if(on&&posed){posed=false;bar.classList.remove('posed');capPose.hidden=true}} // the bar goes on from half way

  // Once per frame: near the top the bar always shows; below that, a move down hides it and a move up brings it back
  // (with "Only near the top", only the top does). lastY changes only on a move past JITTER, so a slow scroll still adds up.
  // The position is clamped, so the rubber-band bounce at either end of a touch scroll does not count as a move.
  function update(){
    ticking=false;
    const y=Math.min(Math.max(scroller.scrollTop,0),maxY);
    place(y); // the marker and the copy move on every scroll, before the early returns
    if(y<=nearTop){setAway(false);lastY=y;return}
    const dy=y-lastY;
    if(Math.abs(dy)<JITTER)return;
    if(dy>0)setAway(true);
    else if(comeBack==='any')setAway(false);
    dir=dy>0?'down':'up';words(); // only a move that is judged changes the arrow
    lastY=y;
  }
  scroller.addEventListener('scroll',()=>{
    const y=scroller.scrollTop;
    // a move up lifts the pose; a move down keeps it until the bar leaves, so the bar only ever moves one way
    if(mode==='compare'&&!(posed&&y===posedAt)){if(posed&&y<seenY)setPose(false);schedulePose()}
    seenY=y;
    if(!ticking){ticking=true;requestAnimationFrame(update)}
  },{passive:true});

  // Slow motion makes the slide and Show me's glides three times longer (not the hold between them)
  function slow(){return slowTog.checked?3:1}
  function applySpeed(){vars.setProperty('--dur',ms*slow()+'ms');words()}
  slowTog.addEventListener('change',applySpeed);
  // The shared script switches Slow motion off without a change event when reduced motion turns on: read it again after it
  motionMQ.addEventListener('change',()=>setTimeout(applySpeed,0)); // applySpeed writes the views' words again

  // Show me: one run, every timer and frame of it kept so stopRun() ends it at once
  function running(){return runFrame!==0||runTimers.length>0}
  function stopRun(){cancelAnimationFrame(runFrame);runFrame=0;runTimers.forEach(clearTimeout);runTimers=[]}
  function later(fn,wait){const id=setTimeout(()=>{runTimers=runTimers.filter(t=>t!==id);fn()},wait);runTimers.push(id)}
  const ease=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;
  // Scrolls the page to `to` over `time` ms; the position on each frame comes from the time since the start
  function glide(to,time,done){
    const from=scroller.scrollTop;let start=null;
    function step(now){
      if(start===null)start=now;
      const t=Math.min((now-start)/time,1);
      scroller.scrollTop=from+(to-from)*ease(t);
      runFrame=t<1?requestAnimationFrame(step):0;
      if(t>=1&&done)done();
    }
    runFrame=requestAnimationFrame(step);
  }
  // The page glides down one and a half boxes (up instead when there is no room below), holds, and glides back to where it
  // began. Under reduced motion it jumps instead: down, halfway back (where only "On any scroll up" brings the bar back), home.
  document.getElementById('btn-demo').addEventListener('click',()=>{
    const again=running(); // pressed during a run: it begins again from the same place
    stopRun();measure();
    const from=again?runFrom:scroller.scrollTop,span=Math.round(scroller.clientHeight*1.5);
    const far=from+span<=maxY?from+span:Math.max(0,from-span);
    runFrom=from;
    if(motionMQ.matches){
      scroller.scrollTop=far;
      later(()=>{scroller.scrollTop=Math.round((from+far)/2)},1000);
      later(()=>{scroller.scrollTop=from},2000);
      return;
    }
    glide(far,MOVE*slow(),()=>later(()=>glide(from,MOVE*slow()),HOLD));
  });
  // Reset: back to the top with the bar in place, at once
  document.getElementById('btn-reset').addEventListener('click',()=>{
    stopRun();
    bar.classList.add('snap');
    scroller.scrollTop=0;lastY=0;setAway(false);dir=null;words();place(0);
    void bar.offsetWidth;
    bar.classList.remove('snap');
    if(mode==='compare'){clearTimeout(poseTimer);setPose(false,true);setPose(true,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('speed-seg',d=>{ms=+d.ms;applySpeed()});
  choices('back-seg',d=>{comeBack=d.back;words()});
  shrinkTog.addEventListener('change',()=>{stage.classList.toggle('shrink',shrinkTog.checked);words()});

  // ── See inside and Compare ──
  const fx=stage.querySelector('.fx'),fxIn=fx.querySelector('.fx-in'),trk=fx.querySelector('.trk'),zone=fx.querySelector('.zone'),mk=fx.querySelector('.mk');
  const q=s=>fx.querySelector(s),capMv=q('.cap-mv span'),capBot=q('.cap-bot'),capN2=q('.cap-n2'),capPose=q('.cap-pose'),capRules=q('.cap-rules');
  const cpage=q('.cpage'),notes={inside:document.querySelector('[data-hb-for="inside"]'),compare:document.querySelector('[data-hb-for="compare"]')};
  const NOTE0={inside:notes.inside.textContent,compare:notes.compare.textContent};
  const put=(el,t)=>{if(el.textContent!==t)el.textContent=t};
  // The top half is a copy of the page, made once: no ids to repeat, inert and hidden from screen readers with its layer
  cpage.append(scroller.querySelector('.post').cloneNode(true));
  const bcopy=bar.cloneNode(true);bcopy.removeAttribute('id');bcopy.removeAttribute('aria-hidden');q('.h1').append(bcopy);
  const NOTES={ // the markup holds the default words; these replace them for Shrinks and for reduced motion
    inside:{rm:"Shown without sliding, as your device asks: the bar fades. In the track's shaded top zone it always shows; the arrow is the last move that counted.",
      rmShrink:"Shown without sliding, as your device asks: the slim strip appears at once. In the track's shaded top zone the whole bar always shows; the arrow is the last move that counted."},
    compare:{shrink:"Always there keeps the bar, so less of the page shows; Shrinks on scroll leaves a slim strip on the way down, half way at rest. Scroll, or press Show me.",
      rm:"Shown still: Always there keeps the bar; Hides on scroll fades its bar out as you scroll down, shown half faded at rest.",
      rmShrink:"Shown still: Always there keeps the whole bar; Shrinks on scroll leaves only a slim strip once you scroll down, as shown here."}};
  const span=t=>t<=200?'a sixth of a second':t<=400?'a third of a second':t<=550?'half a second':t<=800?'two thirds of a second':t<=1200?'a second':'two seconds';
  function label(){
    const gone=shrinkTog.checked?'shrinks to a strip':'slides away';
    return ['A page whose top bar slides away as you scroll down',
      'A page whose top bar '+gone+' as you scroll down, with a track of the page, its top zone and the last move',
      'The page twice, one above the other: a bar that always stays, and a bar that '+gone+' as you scroll down'][['normal','inside','compare'].indexOf(mode)];
  }
  // Every word the views write comes from the page's own state: Speed and Slow motion, Comes back, Shrinks, reduced motion, the last move
  function words(){
    const rm=motionMQ.matches,sh=shrinkTog.checked,home=comeBack==='top',key=rm?(sh?'rmShrink':'rm'):sh?'shrink':'';
    const how=rm?(sh?'a strip appears at once':'it fades away'):sh?'it shrinks to a strip':'it slides away';
    const back=rm?(sh?'the whole bar returns at once':'it fades back'):sh?'it grows back':'it slides back';
    fxIn.dataset.dir=dir||'none';
    put(capMv,dir==='down'?'Moved down: '+how:dir==='up'?'Moved up: '+(home?(sh?'it stays a strip until the top':'it stays away until the top'):back)
      :'Example: a move down '+(rm?(sh?'leaves a strip':'fades it'):sh?'shrinks it':'hides it'));
    put(capBot,'Moves of a few pixels do not count; '+(rm&&sh?'the strip appears at once':(sh?'it shrinks':rm?'it fades':'it slides')+' in about '+span(ms*slow()))+'; back '+(home?'only near the top':'on any scroll up'));
    put(capN2,sh?'Shrinks on scroll':'Hides on scroll');
    put(capPose,rm?(sh?'Shrunk to a strip':'Half faded'):sh?'Half way shrunk':'Half way hidden');
    put(capRules,(rm&&sh?'At once':'Takes about '+span(ms*slow()))+'; back '+(home?'only near the top':'on any scroll up'));
    for(const m in notes)put(notes[m],(NOTES[m]&&NOTES[m][key])||NOTE0[m]);
    if(mode!=='normal')scroller.setAttribute('aria-label',label());
  }
  // The track is measured here (when the mode, the size or the text changes), never once per scroll frame
  function fit(){
    trackH=trk.clientHeight;
    zone.style.height=(maxY>0?Math.min(1,nearTop/maxY):1)*trackH+'px';
    place(Math.min(Math.max(scroller.scrollTop,0),maxY));
  }
  function place(y){
    if(mode==='inside')mk.style.transform='translateY('+(maxY>0?y/maxY*trackH:0)+'px)';
    else if(mode==='compare')cpage.style.transform='translate3d(0,'+-y+'px,0)';
  }
  if(window.ResizeObserver)new ResizeObserver(fit).observe(trk);
  // Compare's real bar is posed half way through leaving while the box rests with the bar showing; a scroll or Show me lifts the pose
  function setPose(on,instant){
    if(on===posed)return;
    posed=on;posedAt=scroller.scrollTop;
    if(instant)bar.classList.add('snap');
    bar.classList.toggle('posed',on);capPose.hidden=!on; // its label is there only while the bar is posed
    if(instant){void bar.offsetWidth;bar.classList.remove('snap')}
  }
  function schedulePose(){
    clearTimeout(poseTimer);
    if(mode==='compare')poseTimer=setTimeout(function again(){if(running())poseTimer=setTimeout(again,POSE);else setPose(!away)},POSE);
  }
  // A wheel turn over the top half (a copy) scrolls the real box, unless the box is at that end and the page should scroll
  stage.addEventListener('wheel',e=>{
    if(mode!=='compare'||scroller.contains(e.target))return;
    const dy=e.deltaMode===1?e.deltaY*16:e.deltaMode===2?e.deltaY*scroller.clientHeight:e.deltaY,y=scroller.scrollTop;
    if(dy<0&&y<=0||dy>0&&y>=maxY-1)return;
    e.preventDefault();scroller.scrollTop=y+dy;
  },{passive:false});

  window.addEventListener('resize',measure);
  if(document.fonts&&document.fonts.ready)document.fonts.ready.then(measure);
  measure();applySpeed();
</script>
</body>
</html>