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.

32.3 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>Error Shake — Animation Handbook</title>
  <meta name="description" content="A field shakes side to side when the input is wrong. Best for sign-in forms.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/error-shake/">
  <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="Error Shake — Animation Handbook">
  <meta property="og:description" content="A field shakes side to side when the input is wrong. Best for sign-in forms.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/error-shake/">
  <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="Error Shake — Animation Handbook">
  <meta name="twitter:description" content="A field shakes side to side when the input is wrong. Best for sign-in forms.">
  <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": "Error Shake", "name": "Error Shake", "description": "A field shakes side to side when the input is wrong. Best for sign-in forms.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/error-shake/", "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, Error Shake"}</script>
  <style>
    :root{--bg:#0b0b0d;--ui-accent:#ff9d5c;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-text:#f4f4f2;--ui-muted:#8a8a92;--err:#f4515b;--ok:#3fb950;--shake-x:8px;--shake-dur:400ms;--shake-ease:cubic-bezier(.36,.07,.19,.97);--pose-k:-.857}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{display:flex;align-items:center;justify-content:center;padding:clamp(16px,4vw,32px);background:var(--bg)}
    /* Login card */
    .card{width:100%;max-width:320px;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:12px;padding:24px;display:flex;flex-direction:column;gap:14px}
    .card-title{font-weight:700;font-size:15px}
    .field{display:flex;flex-direction:column;gap:6px}
    .field label,.twin .lab{font-size:11px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-muted)}
    .field input,.twin .box{background:var(--bg);border:1.5px solid var(--ui-border);color:var(--ui-text);font-family:inherit;font-size:13px;padding:11px 12px;border-radius:7px;width:100%;min-height:44px;outline:none;transition:border-color .18s}
    .field input::placeholder{color:var(--ui-muted);opacity:1}
    .field input:focus{border-color:var(--ui-accent)}
    /* While the field is neutral it draws its own focus (the border), so the site ring is switched off; .stage in front outranks it (0,5,1).
       In the error and success states the border is red or green with or without focus, so there the site ring stays and shows it */
    .stage .field:not(.error):not(.ok) input:focus-visible{outline:none}
    /* Error state: red border + shake keyframe */
    .field.error input,.twin .field.error .box{border-color:var(--err)}
    .field.error input{animation:shake var(--shake-dur) var(--shake-ease) both}
    .msg{font-size:11px;min-height:14px;color:var(--err);opacity:0;transform:translateY(-2px);transition:opacity .18s,transform .18s}
    .field.error .msg{opacity:1;transform:none}
    .field.ok input,.twin .field.ok .box{border-color:var(--ok)}
    .field.ok .msg{opacity:1;transform:none;color:var(--ok)}
    /* buildShake() rewrites this rule when the page loads, with swings that decay (six by default); this copy only stands in until then. translateX only -> compositor-friendly. */
    @keyframes shake{
      10%,90%{transform:translateX(calc(var(--shake-x) * -1))}
      20%,80%{transform:translateX(calc(var(--shake-x) * 1))}
      30%,50%,70%{transform:translateX(calc(var(--shake-x) * -0.6))}
      40%,60%{transform:translateX(calc(var(--shake-x) * 0.6))}
      100%{transform:translateX(0)}
    }
    .submit{background:var(--ui-accent);border:none;color:#1a0f08;font-family:inherit;font-weight:700;font-size:12px;padding:13px;border-radius:7px;cursor:pointer;min-height:44px;transition:filter .15s}
    @media(hover:hover){.submit:hover{filter:brightness(1.08)}}
    .submit:active{filter:brightness(.94)}
    /* The button is filled with the accent colour, so the site ring (the same colour) would vanish on it: a dark ring instead */
    .hb-page .stage .submit:focus-visible{outline-color:#0b0b0d}
    /* Read out by screen readers only */
    .sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
    /* Phones zoom the page in on a field with type smaller than 16px */
    @media(pointer:coarse){.field input,.twin .box{font-size:16px}}
    /* See inside and Compare. Their labels are plain words on a dark backing. */
    .twin,.trace,.side,.ghost{display:none}
    .lbl{position:absolute;padding:2px 7px;border:1px solid rgba(244,244,242,.16);border-radius:5px;background:rgba(11,11,13,.9);color:var(--ui-text);font:600 12px/15px var(--hb-font);white-space:nowrap}
    .twin .box{display:flex;align-items:center;overflow:hidden;white-space:nowrap}
    .twin .box.ph{color:var(--ui-muted)}
    .twin .submit{display:flex;align-items:center;justify-content:center;cursor:default}
    .stage[data-hb-mode="inside"],.stage[data-hb-mode="compare"]{position:relative}
    /* See inside: the card beside a trace of its shake, level with the field (under the card on phones). The trace is the field's path
       with time running down, drawn five times as wide as the field moves; the script draws it and its words, and a dot rides it. */
    .stage[data-hb-mode="inside"]{display:grid;grid-template-columns:minmax(0,320px) minmax(0,440px);grid-template-rows:minmax(0,1fr);justify-content:center;
      column-gap:clamp(12px,3vw,28px)}
    .stage[data-hb-mode="inside"] .trace{display:block;position:relative;align-self:stretch}
    .trace svg{position:absolute;inset:0;width:100%;height:100%;overflow:visible}
    .trace .rest{fill:none;stroke:rgba(244,244,242,.6);stroke-width:1.5;stroke-dasharray:5 4}
    .trace .zig{fill:none;stroke:var(--ui-accent);stroke-width:2.5;stroke-linejoin:round}
    .trace .dot{fill:#f4f4f2}
    .trace .lbl{width:max-content;white-space:normal;text-wrap:balance}
    /* Compare: the card twice. On the left a copy that only turns red, on the right the card itself, which also shakes. At rest both stand
       as just after a wrong password (the pose), the right field held at its first swing beside a dashed outline of its place. */
    .stage[data-hb-mode="compare"]{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));align-content:center;justify-items:center;
      column-gap:clamp(8px,2vw,24px);padding:44px clamp(6px,2vw,24px) 12px}
    .stage[data-hb-mode="compare"]::after{content:'';position:absolute;top:0;bottom:0;left:50%;border-left:1px solid rgba(244,244,242,.12)}
    .stage[data-hb-mode="compare"] .twin{display:flex}
    .stage[data-hb-mode="compare"] .side{display:block}
    .stage[data-hb-mode="compare"] .field{position:relative}
    .side{top:10px;left:10px}
    .side.second{left:calc(50% + 10px)}
    .stage[data-hb-mode="compare"].posed .field:not(.error):not(.ok) :is(input,.box){border-color:var(--err)}
    .stage[data-hb-mode="compare"].posed .field:not(.error):not(.ok) .msg{opacity:1;transform:none}
    .stage[data-hb-mode="compare"].posed .card:not(.twin) .field:not(.error):not(.ok) input{transform:translateX(calc(var(--shake-x) * var(--pose-k)))}
    .stage[data-hb-mode="compare"].posed .card:not(.twin) .ghost{display:block;position:absolute;left:0;right:0;border:1.5px dashed rgba(244,244,242,.5);border-radius:7px;pointer-events:none}
    @media(max-width:600px){
      .stage[data-hb-mode="inside"]{grid-template-columns:minmax(0,320px);grid-template-rows:auto minmax(0,1fr);align-content:stretch;row-gap:2px;padding:4px 10px}
      .stage[data-hb-mode="compare"] .msg{min-height:28px}
    }
    /* Phones and short boxes (a window up to 640px tall): a compact card, so the trace's words and the half names fit */
    @media(max-width:600px),(max-height:640px){
      .stage[data-hb-mode="inside"] .card,.stage[data-hb-mode="compare"] .card{padding:10px 12px;gap:8px}
      .stage[data-hb-mode="inside"] .field,.stage[data-hb-mode="compare"] .field{gap:4px}
      .stage[data-hb-mode="inside"] .card-title,.stage[data-hb-mode="compare"] .card-title{display:none}
    }
    @media(prefers-reduced-motion:reduce){.field.error input{animation:none!important}}
  </style>
  <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
  <script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="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="../cursor-follower/" rel="prev" aria-label="Previous: Cursor Follower"><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>Cursor Follower</span></a><a href="../swipe-to-dismiss/" rel="next" aria-label="Next: Swipe to Dismiss"><span><span class="hb-dir">Next: </span>Swipe to Dismiss</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.21 · Micro-Interactions</p>
    <h1>Error Shake</h1>
    <p class="hb-lede">A field shakes side to side when the input is wrong. Best for sign-in forms.</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>Sign in with a wrong or empty password (the right one is letmein), 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">
      <form class="card" id="login" novalidate>
        <p class="card-title">Sign in</p>
        <div class="field" id="field">
          <label for="pw">Password</label>
          <input type="password" id="pw" autocomplete="off" placeholder="••••••••">
          <span class="msg" id="msg" aria-hidden="true"></span>
        </div>
        <button class="submit" type="submit">Sign in</button>
        <p class="sr-only" id="live" role="alert"></p>
      </form>
      <div class="trace" aria-hidden="true">
        <svg><path class="rest"/><path class="zig"/><circle class="dot" r="6"/></svg>
        <span class="lbl rests" data-hb-caption>Where it rests</span>
        <span class="lbl swings" data-hb-caption>Six swings, each smaller than the last</span>
        <span class="lbl back" data-hb-caption>Back where it started after under half a second</span>
        <span class="lbl wide" data-hb-caption>Drawn five times as wide as it moves</span>
      </div>
      <p class="lbl side first" aria-hidden="true" data-hb-caption>Just turns red</p>
      <p class="lbl side second" aria-hidden="true" data-hb-caption>Shakes too</p>
    </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 zig-zag is the field's path, drawn five times as wide: each swing is smaller than the last, and it ends where it started. Sign in with a wrong password, or press Show me.</p>
      <p data-hb-for="compare" hidden>Just turns red only changes the border and message, which is easy to miss; Shakes too also moves the field, which catches the eye. Sign in with a wrong password, 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 try it again or press Show me.</p></div>
    </div>
    <div class="hb-settings">
      <div class="hb-setting">
        <p class="hb-setting-name" id="dist-lbl">Shake distance</p>
        <div class="seg" id="dist-seg" role="group" aria-labelledby="dist-lbl">
          <button type="button" data-x="4px" aria-pressed="false">Small</button>
          <button type="button" data-x="8px" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-x="14px" aria-pressed="false">Large</button>
        </div>
        <p class="hb-hint">How far the field swings left and right.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="swings-lbl">Number of swings</p>
        <div class="seg" id="swings-seg" role="group" aria-labelledby="swings-lbl">
          <button type="button" data-n="4" aria-pressed="false">Few</button>
          <button type="button" data-n="6" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-n="8" aria-pressed="false">Many</button>
        </div>
        <p class="hb-hint">Four to six swings read as a head shake.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="speed-lbl">Speed</p>
        <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
          <button type="button" data-ms="650" aria-pressed="false">Slow</button>
          <button type="button" data-ms="400" class="on" aria-pressed="true">Normal</button>
          <button type="button" data-ms="250" aria-pressed="false">Fast</button>
        </div>
        <p class="hb-hint">How long the whole shake lasts.</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 an error shake to [the form field that can be rejected, such as a password]. When the value is wrong or missing, move the field quickly left and right a few times, each swing smaller than the last, and end exactly where it started, like a head shaking no. Turn its border red and show a short message saying what went wrong, because movement and color alone do not explain the problem. Move only its horizontal position so the shake stays smooth, and restart the shake on every failed try. If the visitor has reduced motion turned on, skip the shake and keep the red border and the message. 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>Sign-in forms</li><li>Codes and PINs</li><li>Form fields</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Whole pages</li><li>Warnings</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 form=document.getElementById('login');
  const field=document.getElementById('field');
  const input=document.getElementById('pw');
  const msg=document.getElementById('msg');
  const live=document.getElementById('live');
  const root=document.documentElement.style;
  const PASSWORD='letmein';
  const DEMO_PASSWORD='abc123'; // what Show me types in
  let dur=400;                  // the shake's length, which Show me waits for
  let swings=6;                 // Number of swings
  let mode='normal',modeClick=false;

  // Building the keyframe from the oscillation count keeps the demo honest:
  // more oscillations = more decaying swings written into one @keyframes.
  // Swing i of n alternates from the left and shrinks toward the end: where buildShake puts it, and where See inside and Compare draw it
  const swing=(i,n)=>(i%2?-1:1)*(1-i/(n+1));
  function buildShake(count){
    swings=count;
    root.setProperty('--pose-k',swing(1,count).toFixed(3));
    const sheet=document.styleSheets[0];
    // find and drop the old shake rule
    for(let i=sheet.cssRules.length-1;i>=0;i--){
      if(sheet.cssRules[i].name==='shake'){sheet.deleteRule(i);break;}
    }
    let steps='0%{transform:translateX(0)}';
    for(let i=1;i<=count;i++){
      const pos=(i/(count+1))*100;
      steps+=`${pos.toFixed(2)}%{transform:translateX(calc(var(--shake-x) * ${swing(i,count).toFixed(3)}))}`;
    }
    steps+='100%{transform:translateX(0)}';
    sheet.insertRule(`@keyframes shake{${steps}}`,sheet.cssRules.length);
  }

  // Screen readers hear the result through the hidden alert; the message in the field is the same words for the eyes.
  // Only the visitor's own sign-in says anything: a Show me run stays silent.
  let sayTimer=0;
  function say(text){
    clearTimeout(sayTimer);
    live.textContent='';
    sayTimer=setTimeout(()=>{live.textContent=text},60);
  }
  function clearState(){
    field.classList.remove('error','ok');
    clearTimeout(sayTimer);live.textContent='';
    state();
  }

  // The visitor's failed sign-in and Show me both call this
  function shake(text){
    clearState();
    // reflow forces the animation to restart even on repeated failures
    void field.offsetWidth;
    msg.textContent=text;
    field.classList.add('error');
    state();
  }

  form.addEventListener('submit',e=>{
    e.preventDefault();
    const v=input.value.trim();
    if(v===PASSWORD){
      clearState();
      msg.textContent='Welcome back — signed in.';
      field.classList.add('ok');
      state();
    }else{
      shake(v?'Incorrect password. Try again.':'Password is required.');
      if(v)input.select();else input.focus();
    }
    say(msg.textContent);
  });
  input.addEventListener('input',clearState);

  // 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||0) ms: Slow motion triples the movement, never the hold.
  const slowTog=document.getElementById('slow-tog');      // only on pages with Slow motion
  let runTimers=[];
  function later(fn,move,hold){
    const slow=!!(slowTog&&slowTog.checked);
    const id=setTimeout(()=>{ runTimers=runTimers.filter(t=>t!==id); fn(); state(); }, move*(slow?3:1)+(hold||0));
    runTimers.push(id);
  }
  function running(){ return runTimers.length>0; }
  function stopRun(){ runTimers.forEach(clearTimeout); runTimers=[]; }
  function clearField(){input.value='';clearState()}
  // A run starts with an empty field and no error, put there without animating: the transitions are turned off, the field is
  // emptied, a reflow makes it stick, and the transitions come back.
  function toRest(){snap(clearField)}
  // A wrong password appears as dots, the field shakes as it does for a visitor (no submit, no focus, nothing said aloud),
  // and once the shake has run and been seen the field is emptied. The press the shared script makes on arrival leaves a
  // visitor who is already in the form alone: it would empty and replace a password being typed.
  document.getElementById('btn-demo').addEventListener('click',e=>{
    if(!e.isTrusted&&stage.contains(document.activeElement))return;
    // A See inside or Compare press clicks Show me for the visitor: it never empties or replaces a password they typed
    if(modeClick&&input.value&&input.value!==DEMO_PASSWORD)return;
    stopRun();
    toRest();
    input.value=DEMO_PASSWORD;
    later(()=>shake('Incorrect password. Try again.'),0,400);
    later(clearField,dur,2000);
    state();
  });
  // The visitor pressed, typed, scrolled or touched inside the stage: the run stops, and the run's password goes, so the
  // visitor starts from a clean field.
  function takeOver(){
    if(!running())return;
    stopRun();
    state();
    if(input.value===DEMO_PASSWORD)clearField();
  }
  document.addEventListener('hb:input',takeOver);
  // A Tab press from outside the stage sends no hb:input, but a run never moves the focus, so focus arriving in the stage while
  // one runs is the visitor's.
  stage.addEventListener('focusin',e=>{ if(e.isTrusted)takeOver(); });

  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);
      view();
    }));
  }
  choices('dist-seg',d=>root.setProperty('--shake-x',d.x));
  choices('swings-seg',d=>buildShake(+d.n));
  choices('speed-seg',d=>{dur=+d.ms;root.setProperty('--shake-dur',d.ms+'ms')});

  // See inside and Compare ------------------------------------------------------------------------------------------------
  const MAG=5;                  // See inside draws the field's path five times as wide as it moves
  const EASE=getComputedStyle(document.documentElement).getPropertyValue('--shake-ease').match(/[\d.]+/g).map(Number); // the shake's own curve
  const NUMS={4:'Four',6:'Six',8:'Eight'};
  const words=ms=>ms<=300?'a quarter of a second':ms<=450?'under half a second':ms<=700?'about two thirds of a second':ms<=900?'about three quarters of a second':ms<=1300?'just over a second':'about two seconds';
  const POSED_MSG='Incorrect password. Try again.';
  const motionOk=!matchMedia('(prefers-reduced-motion:reduce)').matches;
  const trace=stage.querySelector('.trace'),svg=trace.querySelector('svg'),zig=svg.querySelector('.zig'),rest=svg.querySelector('.rest'),dot=svg.querySelector('.dot');
  const [tRests,tSwings,tBack,tWide]=trace.querySelectorAll('.lbl');
  const notes={inside:document.querySelector('[data-hb-for="inside"]'),compare:document.querySelector('[data-hb-for="compare"]')};
  const setNote=(el,t)=>{if(el.textContent!==t)el.textContent=t};
  const STILL='Shown still, at the first swing: Just turns red stays in place; Shakes too is held away from its dashed outline, as it would be with motion on.';
  const LIVE='With reduced motion on, neither half shakes, so Just turns red and Shakes too look alike: a wrong password shows only as a red border and a message.';
  if(!motionOk){
    setNote(notes.inside,'Inside, shown still: the zig-zag is the path the field takes when motion is on, drawn five times as wide, each swing smaller than the last.');
    setNote(notes.compare,STILL);
  }
  // Compare's first card: a copy that only turns red. No form, input, label link or alert, no ids, out of reach of the keyboard and
  // screen readers; state() makes it show what the real card shows (the dots as dots, the classes, the message).
  const twin=document.createElement('div');
  twin.className='card twin';twin.inert=true;twin.setAttribute('aria-hidden','true');
  twin.innerHTML='<p class="card-title">Sign in</p><div class="field"><span class="lab">Password</span><span class="box"></span><span class="msg"></span></div><span class="submit">Sign in</span>';
  form.before(twin);
  const tf=twin.querySelector('.field'),tb=twin.querySelector('.box'),tm=twin.querySelector('.msg');
  const ghost=document.createElement('span');
  ghost.className='ghost';ghost.setAttribute('aria-hidden','true');field.append(ghost);
  // Runs fn with the fields' transitions off, so it shows at once
  function snap(fn){
    const parts=[input,msg,tb,tm];
    parts.forEach(p=>p.style.setProperty('transition','none','important'));
    fn();
    void field.offsetWidth;
    parts.forEach(p=>p.style.removeProperty('transition'));
  }
  // Compare's rest pose: both cards as just after a wrong password (red border, the message), the right field held at its first swing.
  // A key typed, focus in the form, a red or green field or a Show me run lifts it; it returns when the field is empty and idle.
  function state(focusLeft){
    const on=mode==='compare'&&!input.value&&!field.matches('.error,.ok')&&!running()&&(focusLeft||!form.contains(document.activeElement));
    if(on!==stage.classList.contains('posed'))snap(()=>stage.classList.toggle('posed',on));
    if(mode!=='compare')return;
    if(on)msg.textContent=POSED_MSG;
    tf.className=field.className;
    tm.textContent=msg.textContent;
    const n=input.value.length;
    tb.textContent=n?'•'.repeat(n):input.placeholder;
    tb.classList.toggle('ph',!n);
    if(!motionOk)setNote(notes.compare,on?STILL:LIVE);
  }
  form.addEventListener('focusin',()=>state());
  form.addEventListener('focusout',e=>{if(!form.contains(e.relatedTarget))state(true)});

  // The field's share of the way across a stretch between two keyframes, along the shake's own curve (found by halving)
  function bez(x){
    const [a,b,c,e]=EASE,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);
  }
  let G={cx:0,y0:0,h:0},rideRaf=0;
  // Draws the mode from the page's own numbers; again on a setting, a resize and when the font arrives. See inside: the trace (the
  // dashed rest line, the zig-zag through every swing's turn, sampled along the curve) and its four labels, placed from measured sizes.
  function view(){
    if(mode==='compare'){ghost.style.top=input.offsetTop+'px';ghost.style.height=input.offsetHeight+'px'}
    if(mode!=='inside'||!trace.clientWidth)return;
    const w=trace.clientWidth,h=trace.clientHeight,k=swings+1;
    const dist=MAG*parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--shake-x'));
    const cx=Math.round(dist*(1-1/k))+6;
    const fit=(el,x)=>{el.style.maxWidth=(w-x-2)+'px';el.style.left=x+'px'};
    fit(tRests,0);
    const rw=tRests.offsetWidth,bx=Math.min(Math.max(cx-rw/2,0),w-rw);
    fit(tRests,bx);fit(tWide,Math.round(bx+rw+8));
    // The trace starts level with the field; its two top labels stand in a row above it, the others in a column beside it
    const y0=Math.max(input.offsetTop-trace.offsetTop,Math.max(tRests.offsetHeight,tWide.offsetHeight)+8),y1=h-4,H=y1-y0;
    tRests.style.top=y0-6-tRests.offsetHeight+'px';
    tWide.style.top=y0-6-tWide.offsetHeight+'px';
    const pts=[];
    for(let i=0;i<=swings;i++){
      const v0=i?swing(i,swings):0,v1=i<swings?swing(i+1,swings):0;
      for(let s=i?1:0;s<=8;s++)pts.push([cx+dist*(v0+(v1-v0)*bez(s/8)),y0+H*(i+s/8)/k]);
    }
    // The two lower labels start clear of the widest swing beside them, so they take more room (fewer lines) where the zig-zag has
    // narrowed. Shorter words if the pair still does not fit between the top row and the bottom edge, which a narrow trace can bring.
    const park=(el,at)=>{
      let x=cx+14,t=0;
      for(let i=0;i<6;i++){
        fit(el,x);t=at(el.offsetHeight);
        const need=Math.round(pts.reduce((m,p)=>p[1]>t-4&&p[1]<t+el.offsetHeight+4?Math.max(m,p[0]):m,cx)+12);
        if(need<=x)break;
        x=need;
      }
      el.style.top=t+'px';
    };
    const lay=short=>{
      tSwings.textContent=NUMS[swings]+' swings, each smaller'+(short?'':' than the last');
      tBack.textContent=(short?'Back at rest after ':'Back where it started after ')+words(dur*(slowTog.checked?3:1));
      park(tBack,hb=>h-hb);
      park(tSwings,hs=>Math.min(Math.max(y0+H*2/k-hs/2,y0-3),tBack.offsetTop-hs-3));
      return tSwings.offsetTop>=y0-3;
    };
    lay(false)||lay(true);
    svg.setAttribute('viewBox',`0 0 ${w} ${h}`);
    rest.setAttribute('d',`M${cx} ${y0}V${y1}`);
    zig.setAttribute('d','M'+pts.map(p=>p[0].toFixed(1)+' '+p[1].toFixed(1)).join('L'));
    G={cx,y0,h:H};
    placeDot();
  }
  // The dot rides the trace while the field shakes: down with the animation's progress, sideways with the field's offset (five
  // times over), both read from the real animation, so Slow motion slows it too. Between shakes it waits at the top.
  function placeDot(){
    const a=input.getAnimations().find(x=>x.animationName==='shake'),run=!!a&&a.playState==='running';
    const t=run?getComputedStyle(input).transform:'none';
    const x=t==='none'?0:new DOMMatrix(t).m41*MAG;
    dot.style.transform=`translate(${G.cx+x}px,${G.y0+(run?G.h*(a.effect.getComputedTiming().progress||0):0)}px)`;
    return run;
  }
  function ride(){
    cancelAnimationFrame(rideRaf);
    const step=()=>{rideRaf=placeDot()&&mode==='inside'?requestAnimationFrame(step):0};
    step();
  }
  stage.addEventListener('animationstart',e=>{if(mode==='inside'&&e.animationName==='shake')ride()});

  // The mode switch: draws the mode at once. The shared script then presses Show me (not under reduced motion), which plays it. That
  // press runs right after this event, so a flag lets the Show me handler tell it from the visitor's own press.
  document.addEventListener('hb:mode',e=>{
    mode=e.detail.mode;
    modeClick=true;
    queueMicrotask(()=>{modeClick=false});
    state();
    view();
    if(mode==='inside')ride();
  });
  const redraw=new ResizeObserver(view);
  redraw.observe(stage);redraw.observe(trace);
  document.fonts.ready.then(view);
  slowTog.addEventListener('change',view);

  buildShake(6);
</script>
</body>
</html>