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.

fix: Magnetic Button's views keep each pointer in its own half and the copy on one line, the lean arrow moves with the button, and See inside says when the pointer is out of reach

matind3ab323f7879
diff --git a/animations/04-micro-interactions/magnetic-button/index.html b/animations/04-micro-interactions/magnetic-button/index.html
index 0314a115..b97c7c16 100644
--- a/animations/04-micro-interactions/magnetic-button/index.html
+++ b/animations/04-micro-interactions/magnetic-button/index.html
@@ -31,10 +31,9 @@
/* 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 from where the button rests to where it is pulled, 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. */
+ /* 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}
@@ -52,17 +51,20 @@
.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 button twice, side by side (one above the other on phones): on the left a copy that stays put, on the right
- the real one. The copy sits in the middle of its half; the real button keeps its place in the layout and the script moves
- it to the middle of its half with translate, so Normal finds it where it was (moved by layout and back, its words came back
- drawn a fraction of a pixel off). */
- .stage[data-hb-mode="compare"] .twin{display:inline-block;position:absolute;left:25%;top:50%;translate:-50% -50%}
- .cmp-l{top:12px}
- .cmp-l.first{left:12px}
+ /* 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){
@@ -110,14 +112,11 @@
<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 in-l" id="l-label" data-hb-caption>Its label moves a little more</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>
- <g class="ghost" id="ghost"><path d="M0 0V19L5 14.5L8.5 22L11.5 20.7L8 13.3H14.5Z"/></g>
- </svg>
+ <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">
@@ -204,33 +203,53 @@
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'),label:$('l-label')};
- let mode='normal',P=null,mouseIn=false,shift={x:0,y:0};
+ 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 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
- const tx=dx*strength*f,ty=dy*strength*f;
- btn.style.setProperty('--tx',tx+'px');btn.style.setProperty('--ty',ty+'px');
- label.style.transform=`translate(${tx*0.35}px,${ty*0.35}px)`;
- drawViews();
- }else home();
+ 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(){
- btn.style.removeProperty('--tx');btn.style.removeProperty('--ty');label.style.transform='';
- P=null;
+ 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}
+ // In Compare a point the page picks itself (the pose, Show me's spots) 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!=='compare')return{x:px,y:py};
+ const ox=stage.clientLeft,oy=stage.clientTop,W=stage.clientWidth,H=stage.clientHeight,c=restCenter(),t=twinCenter();
+ const d={x:c.x-ox-t.x,y:c.y-oy-t.y},top=stackedMQ.matches?H/2:0,left=stackedMQ.matches?0:W/2;
+ let x=Math.min(Math.max(px-ox,left+4),W-19),y=Math.min(Math.max(py-oy,top+4),H-26);
+ 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}}
@@ -240,60 +259,67 @@
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, and the button leaning toward it as
- // the pull would lean it from its resting place
+ // 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,px=c.x+k*.8,py=c.y-k*.6;
- const tx=(px-c.x)*strength*.5,ty=(py-c.y)*strength*.5;
- btn.style.setProperty('--tx',tx+'px');btn.style.setProperty('--ty',ty+'px');
- label.style.transform=`translate(${tx*0.35}px,${ty*0.35}px)`;
- P={x:px,y:py};
+ 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')return;
- const c=restCenter(),ox=stage.clientLeft,oy=stage.clientTop,cx=c.x-ox,cy=c.y-oy;
- const tx=parseFloat(btn.style.getPropertyValue('--tx'))||0,ty=parseFloat(btn.style.getPropertyValue('--ty'))||0;
- const bw=btn.offsetWidth,bh=btn.offsetHeight;
+ 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);
- // The lean as an arrow, from where the button rests to where the pull has taken its center (none while it rests), with two
- // short head strokes, drawn over a dark edge so the button's words stay readable under it
- const len=Math.hypot(tx,ty),ang=Math.atan2(ty,tx),hx=cx+tx,hy=cy+ty,head=Math.min(9,len/2);
- const arrow=len<1?'':`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);
stage.classList.toggle('pretend',!!P&&!mouseIn);
- toward.style.display=ghost.style.display=P?'':'none';
+ // 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 s=stage.getBoundingClientRect(),tb=twin.getBoundingClientRect();
- const t={x:tb.left+tb.width/2-s.left-ox,y:tb.top+tb.height/2-s.top-oy};
+ 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);
+ 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 8px, too short to read
+ 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<8?'':`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);
}
- // See inside's four labels, each beside the part it names, kept inside the stage and clear of each other. The two about the
- // button sit under its resting place, or over it while the pointer is below the button. The one for the lean takes the first
- // place by the pointer that covers neither the button (where the pull takes it), the pointer nor a label.
- function placeLabels(cx,cy,tx,ty){
+ 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;
- 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,lh=L.label.offsetHeight;
- // Where the whole box is within reach, the ring is outside it
- L.reach.textContent=Math.hypot(Math.max(cx,W-cx),Math.max(cy,H-cy))<radius?'Pulls anywhere in this box':'Pulls inside this ring';
- const up=p.y>cy+bh/2,y1=up?cy-bh/2-12-rh:cy+bh/2+12,y2=up?y1-6-lh:y1+rh+6;
- // what the lean's label must keep clear of, labels first (weight 9) and then the button and the pointer (weight 1)
+ 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,y1)),put(L.label,fit(L.label,cx-L.label.offsetWidth/2,y2)),
+ 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<3?9:1):0),0);
+ 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));
@@ -347,8 +373,7 @@
// 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 pretend pointer is drawn, so the first
- // key moves it on from where it is shown.
+ // 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()});
@@ -371,12 +396,12 @@
// 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.
+ // 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();
- const c=restCenter();
- SPOTS.forEach(([ox,oy],k)=>later(()=>pull(c.x+ox*radius,c.y+oy*radius),k*550,k*150));
+ 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.