A line that draws itself
Hover a link in the navigation here and a loop gets drawn around it, like someone circling a word in a notebook. It’s an old trick, but a couple of details make it much nicer to work with.
The trick
An SVG stroke can be dashed. If a single dash is as long as the whole path and you push it
away with stroke-dashoffset, the line disappears. Animate the offset back to zero and it
looks like a pen is drawing it.
The annoying part used to be measuring the path, because the dash has to match its length.
You’d call getTotalLength() in JavaScript and copy the number into CSS. With pathLength,
you don’t have to:
<svg viewBox="0 0 90 34" aria-hidden="true">
<path d="M8 18C10 6 70 4 82 15 92 26 40 34 14 25" pathLength="1" />
</svg>
pathLength="1" tells the browser to treat the path as one unit long, whatever its real
length. Now every path, short or long, can share the same CSS:
.loop path {
stroke-dasharray: 1 2;
stroke-dashoffset: 1.01;
transition: stroke-dashoffset 900ms cubic-bezier(0.6, 0.05, 0.3, 1);
}
a:hover .loop path,
a[aria-current='page'] .loop path {
stroke-dashoffset: 0;
}
The dots
My first version used stroke-dasharray: 1, which means a dash of 1 and a gap of 1. It
worked, except every hidden loop left a tiny dot behind.
The culprit was stroke-linecap: round. A round cap sticks out past the end of a dash by half
the stroke width, so even with the dash pushed fully out of view, the cap of the next dash
peeked in at the start of the path. Two small changes fixed it:
- Make the gap twice as long as the path (
1 2), so nothing follows the dash. - Push the dash a hair further than its length (
1.01), so its cap clears the start too.
Making it feel handwritten
A perfect ellipse looks like a UI component, not a pen. The loops here are generated at build time: points around an oval, with the radius drifting outward as it goes, a slow wobble, a slight tilt, and an overshoot past where it started. Each link seeds the randomness with its own URL, so every loop is a little different but stays the same between builds.
The easing matters too. A pen starts slowly, moves quickly through the middle and slows down to
finish, so the curve is closer to cubic-bezier(0.6, 0.05, 0.3, 1) than to the usual ease-out.
Respecting reduced motion
If someone has asked their system for less motion, the loop should still show which page
they’re on, just without being drawn. A single global rule shortens transitions to a
millisecond under prefers-reduced-motion: reduce, so the loop simply appears. No extra code
in each component.