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.

31.4 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>Magnetic Button — Animation Handbook</title>
  <meta name="description" content="Leans toward the pointer, then springs home. Best for one main button.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/magnetic-button/">
  <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="Magnetic Button — Animation Handbook">
  <meta property="og:description" content="Leans toward the pointer, then springs home. Best for one main button.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/magnetic-button/">
  <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="Magnetic Button — Animation Handbook">
  <meta name="twitter:description" content="Leans toward the pointer, then springs home. Best for one main button.">
  <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": "Magnetic Button", "name": "Magnetic Button", "description": "Leans toward the pointer, then springs home. Best for one main button.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/04-micro-interactions/magnetic-button/", "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, Magnetic Button"}</script>
  <style>
    :root{--ui-accent:#ff9d5c}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;display:flex;align-items:center;justify-content:center;overflow:hidden;background:#0b0b0d;touch-action:manipulation}
    /* The button and its label move by transform only: --tx and --ty carry the pull, so the pressed size can be added to it */
    .mag{position:relative;border:none;cursor:pointer;background:var(--ui-accent);color:#1a0e05;font-family:inherit;font-weight:700;font-size:clamp(15px,2vw,18px);letter-spacing:.01em;padding:20px 40px;min-height:56px;border-radius:40px;transform:translate(var(--tx,0px),var(--ty,0px));transition:transform .55s cubic-bezier(.22,1,.36,1);will-change:transform}
    .mag.pressed{transform:translate(var(--tx,0px),var(--ty,0px)) scale(.94)}
    .mag .mag-label{display:inline-block;transition:transform .55s cubic-bezier(.22,1,.36,1);will-change:transform}
    /* The site focus ring is drawn inside the button. It has the same orange as the fill, so it turns dark. */
    .hb-page .stage .mag:focus-visible{outline-color:#0b0b0d}
    @media(prefers-reduced-motion:reduce){.mag,.mag .mag-label{transition:transform .12s linear}}
    /* See inside and Compare, drawn over the stage from the page's own numbers: the ring the pull reaches, the button's resting
       place, the lean (an arrow over a dark edge, so the button's words stay readable under it), a faint line to the pointer, a
       pretend pointer, and in Compare a ghost of the pointer over the copy that stays put. */
    .twin,.views,.lbl{display:none}
    .views{position:absolute;inset:0;pointer-events:none}
    .views svg{position:absolute;inset:0;width:100%;height:100%;overflow:visible}
    .ring,.rest,.lean-edge,.lean,.toward,.pointer,.ghost{display:none}
    .ring{fill:rgba(255,157,92,.06);stroke:rgba(255,157,92,.75);stroke-width:2;stroke-dasharray:6 6}
    .rest{fill:none;stroke:rgba(244,244,242,.6);stroke-width:2;stroke-dasharray:5 5}
    .lean-edge{fill:none;stroke:#0b0b0d;stroke-width:6;stroke-linecap:round;stroke-linejoin:round}
    .lean{fill:none;stroke:#f4f4f2;stroke-width:3;stroke-linecap:round;stroke-linejoin:round}
    .toward{stroke:rgba(244,244,242,.45);stroke-width:1.5;stroke-dasharray:3 5}
    .pointer path,.ghost path{fill:#f4f4f2;stroke:#0b0b0d;stroke-width:1.5;stroke-linejoin:round}
    .ghost{opacity:.7}
    .lbl{position:absolute;padding:3px 7px;border-radius:5px;background:rgba(11,11,13,.88);color:#f4f4f2;font:600 13px/1.2 var(--hb-font);white-space:nowrap}
    .stage[data-hb-mode="inside"] .views,.stage[data-hb-mode="compare"] .views{display:block}
    .stage[data-hb-mode="inside"] .ring,.stage[data-hb-mode="inside"] .rest,.stage[data-hb-mode="inside"] .lean-edge,
    .stage[data-hb-mode="inside"] .lean,.stage[data-hb-mode="inside"] .toward,.stage[data-hb-mode="compare"] .toward{display:inline}
    .stage[data-hb-mode="inside"].pretend .pointer,.stage[data-hb-mode="compare"].pretend .pointer,.stage[data-hb-mode="compare"] .ghost{display:inline}
    .stage[data-hb-mode="inside"] .in-l,.stage[data-hb-mode="compare"] .cmp-l{display:block}
    /* Compare: the copy that stays put in the middle of the first half (left, or top on phones), the real button in the second.
       The real button keeps its place in the layout and the script moves it with translate: moved by layout and back, its words
       came back drawn a fraction of a pixel off in Normal. */
    .stage[data-hb-mode="compare"] .twin{display:inline-block;position:absolute;left:25%;top:50%;translate:-50% -50%;white-space:nowrap}
    .cmp-l{top:12px;left:12px}
    .cmp-l.second{left:calc(50% + 12px)}
    /* In Compare the pointer and its line keep to the real button's half, and the ghost to the copy's */
    .stage[data-hb-mode="compare"] .views svg{clip-path:inset(0 0 0 50%)}
    .stage[data-hb-mode="compare"] .views .half-one{clip-path:inset(0 50% 0 0)}
    @media(max-width:600px){
      .stage[data-hb-mode="compare"] .twin{left:50%;top:25%}
      .stage[data-hb-mode="compare"] .cmp-l.second{left:12px;top:calc(50% + 8px)}
      .stage[data-hb-mode="compare"] .views svg{clip-path:inset(50% 0 0 0)}
      .stage[data-hb-mode="compare"] .views .half-one{clip-path:inset(0 0 50% 0)}
    }
    /* Under reduced motion the views take their pose at once, with no glide */
    @media(prefers-reduced-motion:reduce){
      .stage[data-hb-mode="inside"] .mag,.stage[data-hb-mode="inside"] .mag .mag-label,
      .stage[data-hb-mode="compare"] .mag,.stage[data-hb-mode="compare"] .mag .mag-label{transition:none}
    }
  </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="../button-press-scale/" rel="prev" aria-label="Previous: Button Press Scale"><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>Button Press Scale</span></a><a href="../toggle-switch/" rel="next" aria-label="Next: Toggle / Switch Slide"><span><span class="hb-dir">Next: </span>Toggle / Switch Slide</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.05 · Micro-Interactions</p>
    <h1>Magnetic Button</h1>
    <p class="hb-lede">Leans toward the pointer, then springs home. Best for one main button.</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">Hover it</h2><p>Move the pointer close to the button (touch near it on a phone, or Tab to it and use the arrow keys), 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="mag twin" aria-hidden="true" inert><span class="mag-label">Get Started</span></div>
      <button class="mag" type="button"><span class="mag-label">Get Started</span></button>
      <div class="views" aria-hidden="true">
        <svg>
          <circle class="ring" id="ring" r="0"/>
          <rect class="rest" id="rest"/>
          <line class="toward" id="toward"/>
          <path class="lean-edge" id="lean-edge"/>
          <path class="lean" id="lean"/>
        </svg>
        <span class="lbl in-l" id="l-reach" data-hb-caption>Pulls inside this ring</span>
        <span class="lbl in-l" id="l-rest" data-hb-caption>Rests here</span>
        <span class="lbl in-l" id="l-lean" data-hb-caption>Leans toward the pointer</span>
        <span class="lbl cmp-l first" data-hb-caption>Stays put</span>
        <span class="lbl cmp-l second" data-hb-caption>Leans toward you</span>
        <!-- The pretend pointer and its ghost, after the labels so they are never hidden under one -->
        <svg><g class="pointer" id="pointer"><path d="M0 0V19L5 14.5L8.5 22L11.5 20.7L8 13.3H14.5Z"/></g></svg>
        <svg class="half-one"><g class="ghost" id="ghost"><path d="M0 0V19L5 14.5L8.5 22L11.5 20.7L8 13.3H14.5Z"/></g></svg>
      </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 ring shows how far the pull reaches: the button leans part of the way toward the pointer, and its label a little further. Point near it, or press Show me.</p>
      <p data-hb-for="compare" hidden>Stays put: the button ignores the pointer, shown as a ghost. Leans toward you: point near it, or press Show me, and it is pulled toward the pointer.</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="strength-lbl">Pull strength</p>
        <div class="seg" id="strength-seg" role="group" aria-labelledby="strength-lbl">
          <button type="button" data-strength="0.2" aria-pressed="false">Gentle</button>
          <button type="button" data-strength="0.35" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-strength="0.5" aria-pressed="false">Strong</button>
        </div>
        <p class="hb-hint">Stronger pulls feel playful; gentle ones feel calm.</p>
      </div>
      <div class="hb-setting">
        <p class="hb-setting-name" id="reach-lbl">Reach</p>
        <div class="seg" id="reach-seg" role="group" aria-labelledby="reach-lbl">
          <button type="button" data-reach="100" aria-pressed="false">Short</button>
          <button type="button" data-reach="160" class="on" aria-pressed="true">Medium</button>
          <button type="button" data-reach="240" aria-pressed="false">Long</button>
        </div>
        <p class="hb-hint">How close the pointer must come before it pulls.</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 magnetic effect to [the one button you want to stand out]. When the pointer comes within reach, pull the button part of the way toward it, more strongly the closer it gets, and move its label a little further so the label seems to float above the button. When the pointer leaves, let the button spring back to its place. Move it only with transforms so the layout never shifts, and use it on one or two buttons at most. On touch screens, pull the button toward the finger while it touches and send it home when it lifts. If the visitor has reduced motion turned on, move it quickly and evenly instead of letting it glide. 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>Hero buttons</li><li>Portfolio sites</li><li>One key action</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Forms</li><li>Rows of 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.querySelector('.stage');
  const btn=stage.querySelector('button.mag');
  const label=btn.querySelector('.mag-label');
  const slowTog=document.getElementById('slow-tog');
  // See inside and Compare: the copy that stays put, the drawn parts and their labels; P is the point pulling now (null at home)
  const twin=stage.querySelector('.mag.twin');
  const $=id=>document.getElementById(id);
  const ring=$('ring'),rest=$('rest'),toward=$('toward'),lean=$('lean'),leanEdge=$('lean-edge'),pointer=$('pointer'),ghost=$('ghost');
  const L={reach:$('l-reach'),rest:$('l-rest'),lean:$('l-lean')},names=[stage.querySelector('.cmp-l.first'),stage.querySelector('.cmp-l.second')];
  // See inside's note, as the markup has it, and as it reads when the whole box is within reach (the ring is then outside it)
  const insideNote=document.querySelector('[data-hb-for="inside"]'),RING_NOTE=insideNote.textContent,
    WIDE_NOTE='Inside, the pull reaches past the edges of this box: the button leans part of the way toward the pointer, and its label a little further. Point near it, or press Show me.';
  let mode='normal',P=null,mouseIn=false,shift={x:0,y:0},follow=0;
  // Compare stacks its halves where the stage is a phone's
  const stackedMQ=window.matchMedia('(max-width:600px)');
  const hasHover=window.matchMedia('(hover: hover)').matches;
  let strength=0.35,radius=160,runTimers=[];

  // The pull takes a point on the stage (from its top left corner). The mouse, a finger and Show me all call it. It measures from
  // where the button is now, moved or not, and sends the button home when the point is out of reach (the views keep the point, to
  // show where the pull stops). In Compare only a point in the real button's half pulls it.
  function pull(px,py){
    if(mode==='compare'&&!inHalf(px,py)){unpull();P=null;drawViews();return}
    P={x:px,y:py};
    const s=stage.getBoundingClientRect(),b=btn.getBoundingClientRect();
    const dx=px-(b.left+b.width/2-s.left),dy=py-(b.top+b.height/2-s.top),dist=Math.hypot(dx,dy);
    if(dist<radius){
      const f=1-dist/radius; // full strength at the button's center, easing to none at the edge of Reach
      setLean(dx*strength*f,dy*strength*f);
    }else unpull();
    drawViews();
  }
  // The button leans by (tx,ty) and its label a little further
  function setLean(tx,ty){btn.style.setProperty('--tx',tx+'px');btn.style.setProperty('--ty',ty+'px');label.style.transform=`translate(${tx*0.35}px,${ty*0.35}px)`}
  function unpull(){btn.style.removeProperty('--tx');btn.style.removeProperty('--ty');label.style.transform=''}
  // Home: the button goes back to its place. In See inside and Compare, with nothing else pulling it, the pose takes over.
  function home(){
    unpull();P=null;
    if(mode!=='normal'&&idle())pose();else drawViews();
  }
  // Compare: whether a point (in the pull's frame) is in the real button's half
  function inHalf(px,py){return stackedMQ.matches?py-stage.clientTop>=stage.clientHeight/2:px-stage.clientLeft>=stage.clientWidth/2}
  // A point the page picks itself (the pose, Show me's spots) stays inside the box in See inside; in Compare it stays inside the
  // real button's half and clear of its name, and its ghost as clear of the copy's name in the copy's half
  function keep(px,py){
    if(mode==='normal')return{x:px,y:py};
    const ox=stage.clientLeft,oy=stage.clientTop,W=stage.clientWidth,H=stage.clientHeight,cmp=mode==='compare';
    const top=cmp&&stackedMQ.matches?H/2:0,left=cmp&&!stackedMQ.matches?W/2:0;
    let x=Math.min(Math.max(px-ox,left+4),W-19),y=Math.min(Math.max(py-oy,top+4),H-26);
    if(cmp){const c=restCenter(),t=twinCenter(),d={x:c.x-ox-t.x,y:c.y-oy-t.y};
      names.forEach((n,i)=>{const nx=n.offsetLeft+(i?0:d.x),ny=n.offsetTop+(i?0:d.y),nb=ny+n.offsetHeight+6;
        if(x<nx+n.offsetWidth+4&&x+15>nx-4&&y<nb)y=nb})}
    return{x:x+ox,y:y+oy};
  }
  // The copy's center in the drawing's frame (the stage's padding box)
  function twinCenter(){const s=stage.getBoundingClientRect(),b=twin.getBoundingClientRect();return{x:b.left+b.width/2-s.left-stage.clientLeft,y:b.top+b.height/2-s.top-stage.clientTop}}
  // The button's resting center in the pull's frame (the stage's border box): its layout box, which the pull never moves, and in
  // Compare the move to the middle of its half
  function restCenter(){return{x:stage.clientLeft+btn.offsetLeft+btn.offsetWidth/2+shift.x,y:stage.clientTop+btn.offsetTop+btn.offsetHeight/2+shift.y}}
  // Compare: the real button goes to the middle of its half (the right one, or the lower one where they stack) by translate
  function placeHalves(){
    shift=mode!=='compare'?{x:0,y:0}:stackedMQ.matches?{x:0,y:stage.clientHeight/4}:{x:stage.clientWidth/4,y:0};
    btn.style.translate=mode==='compare'?`${shift.x}px ${shift.y}px`:'';
  }
  function idle(){return!mouseIn&&touchId===null&&!keyed&&!running()}
  // The pose: a pretend pointer parked half way to the edge of the ring, up and to the right (in Compare kept in the real button's
  // half), and the button leaning toward it as the pull would lean it from its resting place
  function pose(){
    if(mode==='normal')return;
    const c=restCenter(),k=radius/2,q=keep(c.x+k*.8,c.y-k*.6),dx=q.x-c.x,dy=q.y-c.y,f=Math.max(0,1-Math.hypot(dx,dy)/radius);
    setLean(dx*strength*f,dy*strength*f);
    P=q;
    drawViews();
  }
  // Draws the views for the pull on show (nothing in Normal). The drawing's frame is the stage's padding box.
  function drawViews(){
    if(mode==='normal'){stage.classList.remove('pretend');return}
    const c=restCenter(),ox=stage.clientLeft,oy=stage.clientTop,cx=c.x-ox,cy=c.y-oy,bw=btn.offsetWidth,bh=btn.offsetHeight;
    const tx=parseFloat(btn.style.getPropertyValue('--tx'))||0,ty=parseFloat(btn.style.getPropertyValue('--ty'))||0,leans=Math.hypot(tx,ty)>=.5;
    ring.setAttribute('cx',cx);ring.setAttribute('cy',cy);ring.setAttribute('r',radius);
    rest.setAttribute('x',cx-bw/2);rest.setAttribute('y',cy-bh/2);
    rest.setAttribute('width',bw);rest.setAttribute('height',bh);rest.setAttribute('rx',bh/2);
    stage.classList.toggle('pretend',!!P&&!mouseIn);
    // the line to the pointer only while the pull leans the button; the pointer and its ghost out of reach too
    toward.style.display=P&&leans?'':'none';ghost.style.display=P?'':'none';
    if(P){
      toward.setAttribute('x1',cx);toward.setAttribute('y1',cy);toward.setAttribute('x2',P.x-ox);toward.setAttribute('y2',P.y-oy);
      pointer.setAttribute('transform',`translate(${P.x-ox} ${P.y-oy})`);
      // the ghost: as far from the copy's center as the pointer is from the real button's resting center
      const t=twinCenter();
      ghost.setAttribute('transform',`translate(${t.x+P.x-c.x} ${t.y+P.y-c.y})`);
    }
    if(mode==='inside')placeLabels(cx,cy,tx,ty,leans);
    track();
  }
  // The lean as an arrow from where the button rests to where it is now, drawn again each frame while the button glides so it keeps
  // pace (Slow motion too); none under about 12px, where it would only blot the button's words
  function drawArrow(){
    const c=restCenter(),cx=c.x-stage.clientLeft,cy=c.y-stage.clientTop,m=new DOMMatrixReadOnly(getComputedStyle(btn).transform);
    const len=Math.hypot(m.e,m.f),ang=Math.atan2(m.f,m.e),hx=cx+m.e,hy=cy+m.f,head=Math.min(9,len/2);
    const arrow=len<12?'':`M${cx} ${cy}L${hx} ${hy}M${hx-Math.cos(ang-.6)*head} ${hy-Math.sin(ang-.6)*head}L${hx} ${hy}L${hx-Math.cos(ang+.6)*head} ${hy-Math.sin(ang+.6)*head}`;
    lean.setAttribute('d',arrow);leanEdge.setAttribute('d',arrow);
  }
  function track(){
    cancelAnimationFrame(follow);
    const step=()=>{drawArrow();follow=mode==='inside'&&btn.getAnimations().length?requestAnimationFrame(step):0};
    follow=requestAnimationFrame(step);
  }
  // See inside's three labels, inside the stage and clear of each other. "Rests here" sits under the resting place, or over it while
  // the pointer is below the button. The pointer's label says whether the button leans toward it or it is out of reach, and takes
  // the first place by it that covers no label, nor the button (where the pull takes it) nor the pointer.
  function placeLabels(cx,cy,tx,ty,leans){
    const W=stage.clientWidth,H=stage.clientHeight,ox=stage.clientLeft,oy=stage.clientTop,bw=btn.offsetWidth,bh=btn.offsetHeight;
    const fit=(el,x,y)=>{x=Math.max(6,Math.min(W-el.offsetWidth-6,x));y=Math.max(6,Math.min(H-el.offsetHeight-6,y));return{x,y,r:x+el.offsetWidth,b:y+el.offsetHeight}};
    const put=(el,a)=>{el.style.left=a.x+'px';el.style.top=a.y+'px';return a};
    const hit=(a,b)=>a.x<b.r&&b.x<a.r&&a.y<b.b&&b.y<a.b,say=(el,t)=>{if(el.textContent!==t)el.textContent=t};
    // Where the whole box is within reach, the ring is outside it, and the label and the note say so
    const all=Math.hypot(Math.max(cx,W-cx),Math.max(cy,H-cy))<radius;
    say(L.reach,all?'Pulls anywhere in this box':'Pulls inside this ring');say(insideNote,all?WIDE_NOTE:RING_NOTE);
    say(L.lean,leans?'Leans toward the pointer':'Out of reach');L.lean.style.display=P?'':'none';
    const p=P?{x:P.x-ox,y:P.y-oy}:{x:cx,y:cy},w=L.lean.offsetWidth,h=L.lean.offsetHeight,rh=L.rest.offsetHeight;
    // what the pointer's label must keep clear of, labels first (weight 9) and then the button and the pointer (weight 1)
    const taken=[put(L.reach,fit(L.reach,cx-L.reach.offsetWidth/2,cy-radius-L.reach.offsetHeight-6)),
      put(L.rest,fit(L.rest,cx-L.rest.offsetWidth/2,p.y>cy+bh/2?cy-bh/2-12-rh:cy+bh/2+12)),
      {x:cx+tx-bw/2-4,y:cy+ty-bh/2-4,r:cx+tx+bw/2+4,b:cy+ty+bh/2+4},{x:p.x-2,y:p.y-2,r:p.x+17,b:p.y+24}];
    const cost=a=>taken.reduce((n,o,i)=>n+(hit(a,o)?(i<2?9:1):0),0);
    const tries=[[p.x+20,p.y-h-6],[p.x-w-8,p.y-h-6],[p.x+20,p.y+26],[p.x-w-8,p.y+26],[p.x+22,p.y],[p.x-w-8,p.y],
      [p.x-w/2,cy+ty-bh/2-h-8],[p.x-w/2,cy+ty+bh/2+8]].map(([x,y])=>fit(L.lean,x,y));
    put(L.lean,tries.reduce((m,a)=>cost(a)<cost(m)?a:m));
  }
  function pointAt(e){
    const s=stage.getBoundingClientRect();
    pull(e.clientX-s.left,e.clientY-s.top);
  }

  // Show me: one run at a time. Every timer of the run goes through later(); stopRun() cancels the whole run and sends the button home.
  // 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=[];home()}

  // A mouse pulls while it moves over the stage, and the button goes home when it leaves (only where the device can hover).
  // A run under way is stopped first and the pull runs after it, so the visitor's own pointer takes over at once;
  // leaving the stage ends a run too (stopRun sends the button home), or the run would carry on after the button went home.
  if(hasHover){
    stage.addEventListener('pointerenter',e=>{if(e.pointerType==='mouse')mouseIn=true});
    stage.addEventListener('pointermove',e=>{
      if(e.pointerType!=='mouse')return;
      mouseIn=true;
      if(e.isTrusted&&running())stopRun();
      pointAt(e);
    });
    stage.addEventListener('pointerleave',e=>{if(e.pointerType==='mouse'){mouseIn=false;stopRun()}});
  }
  // A finger or pen pulls while it touches the stage, follows it while it moves and sends the button home when it lifts or leaves the stage
  // (a pen lifted outside would send its pointerup elsewhere).
  // A swipe that scrolls the page cancels the touch. Pointer events, so a tap's follow-up mouse events leave no pointer behind.
  let touchId=null;
  stage.addEventListener('pointerdown',e=>{
    if(e.pointerType==='mouse')return;
    touchId=e.pointerId;pointAt(e);
  });
  stage.addEventListener('pointermove',e=>{if(e.pointerId===touchId)pointAt(e)});
  ['pointerup','pointercancel','pointerleave'].forEach(type=>stage.addEventListener(type,e=>{
    if(e.pointerId!==touchId)return;
    touchId=null;home();
  }));

  // Pressing the button shrinks it a little, for mouse, touch and pen alike.
  btn.addEventListener('pointerdown',()=>btn.classList.add('pressed'));
  ['pointerup','pointercancel','pointerleave'].forEach(type=>btn.addEventListener(type,()=>btn.classList.remove('pressed')));

  // The keyboard: with the button focused, the arrow keys move a pretend pointer from its resting center (kx,ky, in Reach: a
  // tenth of it a press, a held key repeating, up to 1.2, which is out of reach) through the same pull() as the mouse, so the
  // button leans toward it and springs home once it is out of reach. Escape sends the button home, as the mouse leaving does,
  // and so does the focus leaving after the keys pulled it; Space and Enter press it, as a pointer does. Focus arriving stops a
  // run under way, as the mouse moving over the stage does. In See inside and Compare the first key moves the drawn pointer on.
  const ARROWS={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]};
  let kx=0,ky=0,keyed=false;
  btn.addEventListener('focus',()=>{kx=ky=0;if(running())stopRun()});
  btn.addEventListener('blur',()=>{btn.classList.remove('pressed');if(keyed){keyed=false;home()}});
  stage.addEventListener('pointermove',()=>{keyed=false});
  btn.addEventListener('keydown',e=>{
    if(e.altKey||e.ctrlKey||e.metaKey)return;
    if(e.key===' '||e.key==='Enter'){btn.classList.add('pressed');return}
    if(e.key==='Escape'){kx=ky=0;keyed=false;home();return}
    const d=ARROWS[e.key];
    if(!d)return;
    e.preventDefault();
    const c=restCenter();
    if(!keyed&&mode!=='normal'&&P){kx=(P.x-c.x)/radius;ky=(P.y-c.y)/radius}
    kx=Math.max(-1.2,Math.min(1.2,kx+d[0]*.1));ky=Math.max(-1.2,Math.min(1.2,ky+d[1]*.1));
    keyed=true;
    pull(c.x+kx*radius,c.y+ky*radius);
  });
  btn.addEventListener('keyup',e=>{if(e.key===' '||e.key==='Enter')btn.classList.remove('pressed')});

  // A pretend pointer visits three spots around the button: each glide takes 550ms and each spot is held 150ms, then the button goes home.
  // The spots are fixed offsets from the button's resting center, read from its layout box (the pull's transform never moves it) in the
  // pull's own frame, the stage's border box, and sized by Reach so they always fall within it. The center is read again at each
  // spot (a mode pressed during the run moves it), and in Compare each spot is kept inside the real button's half.
  const SPOTS=[[-.55,-.35],[.6,.1],[-.1,.5]];
  document.getElementById('btn-demo').addEventListener('click',()=>{
    stopRun();
    SPOTS.forEach(([sx,sy],k)=>later(()=>{const c=restCenter(),q=keep(c.x+sx*radius,c.y+sy*radius);pull(q.x,q.y)},k*550,k*150));
    later(home,1650,450);
  });
  // The visitor pressed, typed, scrolled or touched inside the stage: the run stops and the button goes home.
  document.addEventListener('hb:input',()=>{if(running())stopRun()});
  // The mode switch: draws the mode at once (in See inside and Compare the pose, in Normal the button at home). The shared script
  // then presses Show me (not under reduced motion), which plays it.
  document.addEventListener('hb:mode',e=>{
    mode=e.detail.mode;
    placeHalves();
    if(idle())home();else drawViews();
  });
  // A new size of the window moves the button's resting place, so the views are drawn again
  addEventListener('resize',()=>{if(mode!=='normal'){placeHalves();if(idle())pose();else drawViews()}});

  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);
      if(mode!=='normal'){if(idle())pose();else drawViews()}
    }));
  }
  choices('strength-seg',d=>{strength=+d.strength});
  choices('reach-seg',d=>{radius=+d.reach});
</script>
</body>
</html>