LightDark
Pull the cord to turn the lights offon
The big idea
Pull the handle down until it turns orange, then let go. The whole site switches theme, and the cord snaps back, overshoots, and swings until it settles. Tap the handle or focus it and press Enter for a quick tug.
Most UI animation is scripted: you say "go from here to there in 300 ms" and the browser fills in the frames. That can't produce this cord. Where it ends up depends on how far you pulled, which way, and how fast you let go. Nobody can write those keyframes in advance.
So instead of describing the motion, we describe the rules and let the motion happen:
- Things keep moving the way they were moving.
- Gravity pulls everything down a little more every moment.
- Air slowly takes energy away.
- A string's pieces stay roughly the same distance apart.
A program that applies rules like these over and over, a tiny slice of time at a time, is a physics simulation. Each slice is called a step. This cord takes 120 steps every second.
Nothing in the code says "swing" or "bounce". Swinging is what you get when those four rules fight each other.
Words you'll need
- Point. A dot with a position,
xandy, in pixels. The cord is a chain of 12 points. - Anchor. The point at the top, nailed to the ceiling. It never moves.
- Velocity. How far a point moves in one step, and in which direction.
- Gravity. A small amount added to the downward velocity every step. Adding speed over time is what acceleration means.
- Damping. Multiplying the velocity by a number just under 1 every step, so motion fades out instead of going on forever.
- Constraint. A rule the simulation enforces after moving things. Here the rule is "these two neighbours should be
SEGMENTpixels apart". - Coordinates. In SVG,
xgrows to the right andygrows downwards, so gravity is a positive number added toy.
How it works
The method is called Verlet integration (said "ver-LAY"). Games use it for cloth, hair, rope, and ragdolls because it's short to write and very hard to make explode. Each step below adds one idea, with a live demo of the cord at that stage.
01 — Draw the cord
Start with what you see: an <svg> with a small mount at the top and one <path> for the cord. A path's d attribute is a list of drawing commands. M x y moves the pen, Q cx cy x y draws a curve that bends towards the control point cx cy, and L x y draws a straight line.
The scene is a fixed 200 × 300 box, and the SVG is drawn at exactly that size, so one SVG unit is one CSS pixel. The anchor sits at the middle of the top edge.
The cord is stored as points. Each point has its current position (x, y) and its previous position (px, py). You'll see why in the next step. For now both are the same, which means "not moving". The orange dots are the points; the dark one is the anchor.
const WIDTH = 200;
const HEIGHT = 300;
const ANCHOR = { x: WIDTH / 2, y: 0 };
const POINTS = 12;
const LENGTH = 130; // rest length of the whole cord
const SEGMENT = LENGTH / (POINTS - 1); // rest length between two neighbouring points
function createRope(): Point[] {
return Array.from({ length: POINTS }, (_, i) => {
const y = ANCHOR.y + i * SEGMENT;
return { x: ANCHOR.x, y, px: ANCHOR.x, py: y };
});
}To turn points into a smooth line, ropePath uses each point as a curve's control point and the midpoint between two points as where the curve passes. That rounds off every corner, so 12 points look like a soft string instead of a zigzag.
function ropePath(points: Point[]) {
const n = (value: number) => value.toFixed(1);
let d = `M ${n(points[0].x)} ${n(points[0].y)}`;
for (let i = 1; i < points.length - 1; i++) {
const a = points[i];
const b = points[i + 1];
d += ` Q ${n(a.x)} ${n(a.y)} ${n((a.x + b.x) / 2)} ${n((a.y + b.y) / 2)}`;
}
const end = points[points.length - 1];
return `${d} L ${n(end.x)} ${n(end.y)}`;
}02 — Give the points motion
Here's the trick that makes Verlet different: velocity isn't stored anywhere. If a point was at px one step ago and is at x now, it moved x - px in one step. That gap is its velocity. To get the next position, repeat that move and add gravity:
next = now + (now − prev) + gravityStep through it with one thrown point. The faint circle is where it was, the orange dot is where it is, the blue arrow repeats the last move, and the green arrow adds gravity. The dashed circle is where it lands.
- now
- 24.0, 196.0
- prev
- -6.0, 232.0
- velocity
- 30.0, -36.0
- gravity
- 0, 4.5
- next
- 54.0, 164.5
Press Step a few times and watch the blue arrow. It starts pointing up and to the right. Each step the green arrow bends it a bit more downwards, and the path traces a curve. That's a thrown ball's arc, and nothing in the code mentions curves.
In code, with damping added, one step looks like this:
- Work out the velocity:
x - px. - Shrink it a little with
damping. Keeping 98.5% each step works like air resistance. - Remember the current position as the previous one.
- Add the velocity, plus
gravityony.
The loop starts at 1 because point 0 is the anchor and never moves. The numbers live in one PHYSICS object so the playground at the end can change them.
export const PHYSICS: Physics = { gravity: 0.12, damping: 0.985, stiffness: 0.5, passes: 6 };
function integrate(points: Point[], { gravity, damping }: Physics) {
for (let i = 1; i < points.length; i++) {
const p = points[i];
const vx = (p.x - p.px) * damping;
const vy = (p.y - p.py) * damping;
p.px = p.x;
p.py = p.y;
p.x += vx;
p.y += vy + gravity;
}
}A handy side effect: to push a point, you don't set a velocity, you just move its previous position. Put px a little to the left of x, and the point now "remembers" moving right, so it keeps going right.
Now run that on the whole cord:
The points fall off the bottom. That's correct. So far they're 11 separate pebbles that happen to start in a line. Nothing says they belong together. Press Replay to drop them again.
03 — Hold them together
A real string doesn't fall apart because each bit is tied to the next. We copy that with a distance constraint: for each pair of neighbours, measure the distance, compare it with the rest length, and move the points to fix the difference.
Try it on a single pair. Drag b around. The dashed circle shows every spot that's exactly the rest length from a. The orange arrow shows where one pass would move b: straight towards or away from a, back towards that circle.
- distance
- 199.8px
- rest
- 80px
- error
- 119.8px · too far apart
- pull
- 0.300
- a moves
- 0% of the fix
- b moves
- 100% of the fix
Things to notice:
- Drag
boutside the circle: the error is positive andbgets pulled in. Drag it inside: the error is negative andbgets pushed out. - With stiffness at
0.5, one pass only fixes half the error. Press Run one pass a few times andbcloses in on the circle: half the gap, then a quarter, then an eighth. - Unpin
a. Now both points move, half each, towards each other. In the cord, the anchor is pinned, so the point under it takes the whole fix. Every other pair splits it.
Why not fix it all at once with stiffness 1? In a chain, fixing one pair moves a point that also belongs to the next pair, which breaks that one. Fixing a bit at a time, over several passes, lets the corrections spread along the chain and settle. Six passes per step is plenty for 12 points.
function pin(p: Point, to: Vec) {
p.x = p.px = to.x;
p.y = p.py = to.y;
}
function constrain(points: Point[], grab: Vec | null, { stiffness, passes }: Physics) {
const last = points.length - 1;
for (let pass = 0; pass < passes; pass++) {
pin(points[0], ANCHOR);
if (grab) pin(points[last], grab);
for (let i = 1; i <= last; i++) {
const a = points[i - 1];
const b = points[i];
const dx = b.x - a.x;
const dy = b.y - a.y;
const distance = Math.hypot(dx, dy) || 1;
const pull = ((distance - SEGMENT) / distance) * stiffness;
// How much of the fix `a` takes. A pinned point takes none of it.
const share = i === 1 ? 0 : grab && i === last ? 1 : 0.5;
a.x += dx * pull * share;
a.y += dy * pull * share;
b.x -= dx * pull * (1 - share);
b.y -= dy * pull * (1 - share);
}
}
}pull divides the error by the distance so that dx * pull and dy * pull together have a length of exactly error × stiffness, pointing along the line between the two points.
Put both rules together and the pebbles become a string:
Here's why it swings, with no swing code anywhere. Replay flicks the bottom to the right. Gravity pulls each point down. The constraints won't let the points get further from the anchor, so falling turns into moving sideways, back towards the middle. When the cord reaches the middle it's still moving, so velocity carries it past. Then gravity slows it, it stops, and it falls back the other way. Damping takes a little energy each step, so every swing is smaller than the last.
04 — Run it at a steady pace
The browser calls requestAnimationFrame once per screen refresh: 60 times a second on most screens, 120 or more on others. If we took one step per frame, the cord would fall twice as fast on a 120 Hz screen.
Instead the loop keeps a balance of time it owes the simulation. Each frame adds the time since the last frame, then pays for as many fixed 8.3 ms steps as it can afford. On a 60 Hz screen that's two steps per frame. On a 120 Hz screen, one. Either way, one second of real time is 120 steps.
If the tab was in the background, the balance could be several seconds. It's capped at 8 steps, so the cord doesn't try to catch up on seconds of physics in one frame.
function tick(now: number) {
// Run as many fixed steps as the elapsed time owes; cap the backlog after a stalled tab.
owed = Math.min(owed + now - last, STEP_MS * 8);
last = now;
// ...
while (owed >= STEP_MS) {
integrate(points, physicsRef.current);
if (stage >= 3) constrain(points, grab.current, physicsRef.current);
owed -= STEP_MS;
}
// ...
draw();draw writes the new path straight onto the <path> element with setAttribute. It doesn't go through React state, because re-rendering a component 120 times a second to change one attribute would be wasted work.
05 — Grab the handle
Now the bottom point gets a handle you can drag. The dashed arc is the cord's rest length: every spot the handle can reach without stretching. The readout in the corner shows how far past that you've pulled.
Pointer events turn your finger or mouse into a second pin:
pointerdowncallssetPointerCapture, so the handle keeps gettingpointermoveevents even when the pointer slides off it.- The pointer position is converted from screen pixels into scene units with
getBoundingClientRect. - While it's held,
grab.currentis set, andconstrainpins the last point there, exactly like the anchor. touch-none(CSStouch-action: none) stops the page from scrolling while you drag on a phone.
function onPointerDown(event: PointerEvent<SVGGElement>) {
if (!canGrab) return;
event.currentTarget.setPointerCapture(event.pointerId);
pressStart.current = toScene(event);
grab.current = clampGrab(pressStart.current);
wake.current();
}Pull below the arc and both ends are pinned further apart than the cord's length. The constraints can't make every segment the right length, so they share the error out evenly and the cord stretches, like a rubber band.
Let go and the bottom is free again. Every segment is too long, so the constraints pull hard, all in the same direction. The points pick up speed upward, overshoot the rest position, and gravity brings them back down into a swing. That springy recoil comes from the same constraint code as the swing.
clampGrab stops the handle at MAX_STRETCH past the cord's length, so you can't drag the cord across the page:
const MAX_STRETCH = 70; // how far past its rest length the cord can be pulled
function clampGrab(to: Vec): Vec {
const dx = to.x - ANCHOR.x;
const dy = to.y - ANCHOR.y;
const distance = Math.hypot(dx, dy) || 1;
const max = LENGTH + MAX_STRETCH;
if (distance <= max) return to;
return { x: ANCHOR.x + (dx / distance) * max, y: ANCHOR.y + (dy / distance) * max };
}06 — Pull to toggle
A real pull switch clicks partway down, and the light changes when you let go. The orange arc is that click point. Pull the handle past it and the switch arms: it plays a click and the handle turns orange. Release while armed and the theme flips. Release before that and the cord just bounces back.
Stretch is measured as a distance from the anchor, which is why the guides are arcs and not straight lines: pulling down and to the side counts too.
const TRIGGER = 38; // pull past this and let go to toggle
function stretchOf(points: Point[]) {
const end = points[points.length - 1];
return Math.hypot(end.x - ANCHOR.x, end.y - ANCHOR.y) - LENGTH;
}
function onPointerMove(event: PointerEvent<SVGGElement>) {
if (!grab.current) return;
grab.current = clampGrab(toScene(event));
if (canToggle) setArmedOnce(stretchOf(rope.current) > TRIGGER);
}
function onPointerUp(event: PointerEvent<SVGGElement>) {
if (!grab.current) return;
const start = pressStart.current!;
const end = toScene(event);
grab.current = null;
pressStart.current = null;
if (canToggle) {
if (armedRef.current) toggle();
else if (Math.hypot(end.x - start.x, end.y - start.y) < 4) tug();
}
setArmedOnce(false);
}Flipping the theme is the same as the site's header button: add or remove the dark class on <html>, set color-scheme so form controls and scrollbars match, and save the choice in localStorage.
function setDark(dark: boolean) {
const root = document.documentElement;
root.classList.toggle("dark", dark);
root.style.colorScheme = dark ? "dark" : "light";
try {
localStorage.setItem("theme", dark ? "dark" : "light");
} catch {
// The theme still changes when storage is unavailable.
}
}A MutationObserver watches that class too, read through React's useSyncExternalStore, so if you switch the theme from the header, the cord's switch state stays in sync.
07 — Keyboard, screen readers, and reduced motion
Dragging is the fun way in, but it can't be the only one.
- The handle has
role="switch",aria-checked, and the label "Dark theme", so a screen reader announces it as "Dark theme, switch, off".tabIndex={0}puts it in the tab order, and a ring shows on:focus-visible. - A tap without dragging, or Enter or Space, calls
tug. It kicks the lower points downward by moving their previous positions up (the same trick as in step 2), then flips the theme straight away.
function tug() {
if (!reducedMotion.current) {
rope.current.forEach((p, i) => (p.py = p.y - 9 * (i / (POINTS - 1)) ** 2));
}
playClick();
toggle();
wake.current();
}- With reduced motion turned on, there's no simulation at all. The cord is a straight line from the anchor to the handle, follows your drag, and jumps straight back when you let go. The toggle works the same way.
function layStraight(points: Point[], end: Vec) {
points.forEach((p, i) => {
const t = i / (points.length - 1);
pin(p, { x: ANCHOR.x + (end.x - ANCHOR.x) * t, y: ANCHOR.y + (end.y - ANCHOR.y) * t });
});
}08 — Let it sleep
A cord that has stopped swinging doesn't need 120 steps a second. After each frame the loop checks whether any point still moved more than a hundredth of a pixel. Once the cord has been still for 30 frames, the loop stops asking for frames. Grabbing, tapping, or pressing a key calls wake, which starts it again. When the component unmounts, the effect cleanup cancels any pending frame.
// Sleep once the rope has been still for half a second.
still = grab.current || isMoving(points) ? 0 : still + 1;
if (still > 30) {
frame = 0;
return;
}
frame = requestAnimationFrame(tick);Playground
Every number in PHYSICS changes how the cord feels. Move a slider, then pull the cord.
- Gravity at
0.03makes the cord float like it's underwater. At0.4it's a heavy chain. - Damping at
0.999barely loses energy, so it swings for ages. At0.9it's like moving through honey. - Stiffness and Passes together decide how stretchy the cord is. One pass with low stiffness is a rubber band. Twenty passes at full stiffness is almost a rigid rod, and the recoil gets snappier.
Why Verlet?
You could give each point a velocity and update it with forces, like a physics textbook. Verlet is nicer here for two reasons:
- Constraints are just moves. When a constraint shoves a point, the next step sees the new position and works out the velocity from it. There's no separate velocity to keep in sync, so constraints can't push the simulation out of control.
- Pushing is easy. To fling, tug, or kick a point, move its previous position. The tug and the Replay buttons in this page both work that way.