2 min read
The scroll spy that highlighted the wrong section
Clicking "Toolkit" in the nav scrolled to precisely the right place and left "Projects" underlined.
The instinct is to blame the scroll. The scroll was correct. Measuring
getBoundingClientRect().top against the header height showed the target landing
exactly where it should, which eliminated the entire family of causes I would
normally have started with: smooth-scroll timing, sticky-header offsets, CSS
transitions on the nav.
The wrong turn
I spent a while looking for a timing race in the scroll handler — the classic cause of a highlight that lags behind. A race clears itself. Scroll a little further, wait a second, and the highlight settles on the right item. This one was stable and wrong indefinitely, and it stayed wrong across reloads, which is the opposite of a race.
A stable, reproducible, wrong-but-consistent result is a logic bug, not a timing bug. Noticing that the highlight never fixed itself was the thing that moved me off the wrong branch.
What it actually was
The spy picked the section to highlight by comparing the scroll position against each section's midpoint, and the arithmetic broke at the boundary: two adjacent sections could both satisfy the condition, and the wrong one won the tie. The resolution was an explicit tie-break plus a small arrival tolerance, so a section that has only just reached the header does not steal the highlight from the one the reader is actually looking at.
The guard
The check clicks each of the four nav links in turn and asserts the underlined link is the one clicked, then does the two things that actually broke: it recrosses a boundary upward, and it scrolls to the very bottom of the document, where no later section exists to claim the highlight and "About" must be pinned.
Recrossing upward is the direction worth testing, because upward crossings are rarer than downward ones in normal use and so are the ones most likely to be wrong without anyone noticing for months.