Photo of Cajaun Campbell

Cajaun Campbell

Software Engineer

Following the Pointer

A walkthrough of a navigation menu where one panel follows your pointer from trigger to trigger and resizes to fit each menu.

Anatomy

A navigation bar with dropdowns gives each section of a site a trigger, and hovering a trigger opens a panel of links underneath it. On this site the triggers would be Work, Writing, Libraries and About, and each one leads to a different group of pages.

My first version gave each trigger a panel of its own. Moving the pointer from Work to Writing faded the Work panel out and faded a second panel in a few pixels to the right, so even though the two panels shared the same style, you read them as two separate objects that happened to sit next to each other.

I wanted you to read the menu as one surface that travels with you. In the version below, hovering a new trigger slides the panel underneath it, and the panel grows or shrinks to fit the new links while the old links fade into the new ones. A small notch on top of the panel points at the trigger you are on, and a pill behind the triggers follows your pointer along the row so you can see which trigger the panel belongs to.

Underneath the motion, the component runs on two pieces of state: one for the menu you opened and one for the trigger under your pointer. I built the pill and the panel on top of those values, and most of the remaining work went into telling a pointer that wants to open a menu apart from a pointer crossing the row on its way to the page.

Before writing any animation code, I limited myself to four properties: transform, opacity, filter and clip-path. Changing one of these leaves the layout of the page untouched, so the browser can repaint the menu on each frame without recalculating where the surrounding elements sit. Animating width or left would force that layout pass on each frame, and on a busy page the menu would stutter as you moved between triggers. That limit decided how I built both the pill and the panel.

Trigger and state

The menu starts as data, with an id, a label and a list of links for each menu.

type MenuId = "work" | "writing" | "libraries" | "about";
 
const MENUS = [
  { id: "work", name: "Work", columns: 2, items: [...] },
  { id: "writing", name: "Writing", columns: 1, items: [...] },
  { id: "libraries", name: "Libraries", columns: 1, items: [...] },
  { id: "about", name: "About", columns: 1, items: [...] },
] as const;

The state needs two values, because the menu has to track two different things at once.

const [open, setOpen] = useState<MenuId | null>(null);
const [hovered, setHovered] = useState<MenuId | null>(null);

open holds the menu that owns the panel, or null once you close the menu. hovered holds the trigger under your pointer, and I use it to place the pill. The two values separate for a moment each time you move from the row into the panel. Your pointer has left the Writing trigger, so hovered goes back to null, but Writing still owns the panel and open keeps it on screen. A single value would close the menu as soon as your pointer left the row.

The preview renders the menu with that state and no animation. Each trigger owns a panel, and the panel that matches open appears in a single frame when you pick a menu.

One value picks the menu. Nothing animates yet

This baseline already behaves like a working menu. I kept it as the foundation and added each visual layer on top of it without introducing a third piece of state.

The pill

The pill is the first thing your pointer reaches, so I built it before the panel. It follows hovered, and when your pointer leaves the row it falls back to open, which keeps it on the trigger that owns the panel.

const pillTarget = hovered ?? open;

That fallback matters as you move down into the panel to pick a link. hovered clears when you leave the row, and the pill slides back to the trigger whose links you are reading, so the row keeps showing which menu you opened.

The triggers have different widths, which means the pill has to change size as well as position when it moves. Animating left and width would handle both, at the cost of a layout pass on each frame. Scaling a fixed pill along the x axis would avoid the layout work, although it would stretch the rounded ends into ovals as the pill grew.

A clip handles the size and the position without either problem. I render the pill as one element that covers the whole list of triggers, and a clip-path trims it down to the box of the trigger under your pointer.

const box = triggers[pillTarget];
const right = listWidth - box.left - box.width;
const bottom = listHeight - box.top - box.height;
 
<span
  className="absolute inset-0 rounded-full bg-black/[0.05]"
  style={{
    clipPath: `inset(${box.top}px ${right}px ${bottom}px ${box.left}px round 999px)`,
    transition: "clip-path 250ms cubic-bezier(0.23, 1, 0.32, 1)",
  }}
/>

Moving the pill comes down to changing the four inset values, and the browser interpolates them for you. The round 999px at the end of the inset keeps both ends round at any width, and the footer tabs on this site use the same technique to move their highlight.

Hover the row, or pick a trigger in the footer

The pill also needs a rule for the moment it first appears. If you move your pointer onto the row after it has been empty for a while, the pill should fade in on the trigger you landed on, because sliding in from the last trigger you visited would drag it across triggers you skipped. To handle that case, I leave clip-path out of the transition on the frame the pill appears.

transitionProperty: wasHidden ? "opacity" : "clip-path, opacity",

On that frame the clip jumps to your trigger while the opacity fades in. From the next move onward the clip transition applies again, so the pill slides between triggers as before.

One panel

The next step replaces the separate panels with a single panel that moves between triggers. To place it, I need the centre of the trigger and the width of the menu the panel is about to show, so I can centre the panel under the trigger and then clamp it inside the edges of the bar.

const size = sizes[shown];
const center = triggers[shown].center;
const left = Math.min(
  Math.max(center - size.w / 2, 0),
  navWidth - size.w,
);
 
<div
  style={{
    transform: `translateX(${left}px)`,
    transition: "transform 300ms cubic-bezier(0.23, 1, 0.32, 1)",
  }}
>
  {panel}
</div>

The clamp exists because of where the menus sit. Work has the widest menu and sits at the left end of the row, so centring its panel under the trigger would push part of the panel past the left edge of the bar. Clamping keeps the panel inside the bar, and About gets the same treatment at the right end.

Once the clamp shifts the panel, the centre of the panel no longer sits under your trigger, which makes it harder to tell which trigger the links belong to. The notch solves that. It is a small square rotated 45 degrees with a border on two sides, and it moves on its own transform so it can point at the trigger while the panel rests against an edge.

<span
  className="absolute -top-[5px] size-2.5 rotate-45 border-l border-t"
  style={{
    transform: `translateX(${center - left - 5}px) rotate(45deg)`,
  }}
/>

I gave the panel and the notch the same duration and easing. The panel stops at the clamp while the notch keeps travelling to the centre of the trigger, and since both start and finish at the same moment, you read them as parts of one object.

The panel stops at the edge of the bar. The notch keeps going to the trigger

The panel reads its position from shown, which falls back to the last menu you opened.

const shown = open ?? lastOpen;

Without that fallback, closing the menu would set open to null and leave the panel with no trigger to sit under, so it would jump before it finished fading out. With shown, the panel stays where you left it and fades out in place.

Resizing with a clip

Each switch also changes the width and height of the panel, since the four menus hold different numbers of links. Transitions on width and height would bring back the per-frame layout work that the clip kept out of the pill, so I applied the same clip to the panel.

I size the panel's box to the largest menu and leave it at that size, and a clip trims the box down to the dimensions of the menu you are looking at.

<div style={{ width: maxW, height: maxH }}>
  <div
    className="absolute inset-0 bg-preview-border"
    style={{
      clipPath: `inset(0 ${maxW - w}px ${maxH - h}px 0 round 16px)`,
    }}
  />
  <div
    className="absolute inset-0 bg-preview-surface"
    style={{
      clipPath: `inset(1px ${maxW - w + 1}px ${maxH - h + 1}px 1px round 15px)`,
    }}
  >
    {menus}
  </div>
</div>

Clipping the panel removes its border, since a CSS border sits on the edge of the box and the clip cuts away everything outside its own shape. I rebuilt the border from two layers. I fill the back layer with the border colour, then fill the front layer with the surface colour and clip it 1 pixel inside the back layer. The 1 pixel ring of the back layer that stays visible reads as the border, and it follows the clip as the panel resizes.

The shadow had the same problem, because a box-shadow draws outside the element and the clip removes it. A drop-shadow filter on the parent element avoids that. The browser applies the filter after it clips the children, which means the shadow traces the visible shape of the panel at each size.

The box stays the size of the largest menu. The clip shows the part you need

The clip also affects hit testing. The browser ignores the trimmed part of the box when it works out what sits under your pointer, so moving off the visible panel counts as leaving the menu even though the full box is still in the document.

I measure each menu once to get its width and height, and a ResizeObserver measures it again when its size changes. That happens on narrow screens, where the two-column Work menu drops to a single column and grows taller.

Crossfading the links

All four menus stay mounted inside the panel, stacked in the top left corner, and the menu on show is the one at full opacity. I set the other three to zero opacity with a 2 pixel blur, and I offset each one 8 pixels toward the side of its own trigger.

const offset = Math.sign(index[id] - index[shown]) * 8;
 
style={{
  opacity: active ? 1 : 0,
  transform: `translateX(${active ? 0 : offset}px)`,
  filter: active ? "blur(0px)" : "blur(2px)",
}}

The offset gives the crossfade a direction that matches the panel. Moving right from Writing to Libraries, you see the Writing links drift left as they fade out while the Libraries links slide in from the right, which is the same direction the panel travels.

The links fade toward the side the panel is moving

The opacity transition lasts 200 milliseconds and the movement lasts 300, so the old links finish fading before the panel reaches its new position. The two menus overlap for a brief moment, but neither stays legible long enough for the two to compete for your attention.

I also mark the hidden menus as inert. Without that attribute, pressing Tab could move focus into links you can't see, and a screen reader would announce all four menus as if they were on screen together.

Hover intent

With the panel and the crossfade in place the menu looks complete, but once you use it with a real mouse you run into two problems.

The first problem appears as your pointer crosses the row on its way to the page below. Each trigger you pass over opens its menu, so a menu flashes open under a pointer that had no intention of stopping. The second problem is the gap between the row and the panel. The panel sits 10 pixels below the row, so your pointer leaves the menu for a moment on its way down, and if the menu closes as soon as the pointer leaves, you can't reach the links.

Both problems come down to timing, so I solved them with two timers.

const enterTrigger = (id: MenuId) => {
  setHovered(id);
  clearTimeout(closeTimer.current);
 
  if (open === null) {
    openTimer.current = setTimeout(() => setOpen(id), 80);
    return;
  }
 
  setOpen(id);
};
 
const leaveMenu = () => {
  setHovered(null);
  clearTimeout(openTimer.current);
  closeTimer.current = setTimeout(() => setOpen(null), 150);
};

Opening waits 80 milliseconds the first time. A pointer passing over the row leaves each trigger before the timer fires, and the leave handler cancels the pending open. Once a menu is open, moving to another trigger switches the panel at once, since the delay exists to confirm the first open and has no job after that.

Closing waits 150 milliseconds, which gives your pointer enough time to cross the gap. The row and the panel also share one wrapper element that carries the pointer handlers. Entering the panel counts as entering the wrapper again, so the enter handler clears the close timer, and leaving the panel starts the timer again.

Sweep across the row, then move down into the panel

The preview starts without the delays. Sweep your mouse across the row and menus open as you pass, then open a menu and move down toward the panel, and it closes before you arrive. Switching to the delays fixes both.

Opening from closed

The slide between triggers is the main reason for having one panel, but it causes a problem when you open the menu from a closed state. If you close the menu while Work is open and then open About, the panel still has the position it had under Work, so it would slide across the whole bar while fading in.

To avoid that, I track whether the previous render had the menu closed.

const prevOpen = useRef(open);
const fromClosed = prevOpen.current === null;
 
useEffect(() => {
  prevOpen.current = open;
}, [open]);
 
const move = fromClosed ? "none" : "300ms cubic-bezier(0.23, 1, 0.32, 1)";

On the render that opens the menu, I turn off the transitions that move and resize the panel and keep the fade. The panel appears under About in its final position, and the switches after that slide as before.

Close the menu, then open the other one. The panel starts under its trigger

Closing needs no extra handling, because shown keeps the last menu and the panel fades out in place.

Touch and keyboard

Phones have no hover state, but a tap still fires pointer events, which means a tap on a trigger would run the hover handlers before the click handler. I check the pointer type in the hover handlers so they ignore touch.

onPointerEnter={(event) => {
  if (event.pointerType !== "mouse") return;
  enterTrigger(id);
}}

On a touch screen, tapping a trigger toggles its menu and tapping outside the menu closes it.

The click handler needs one guard for the mouse. Hovering a trigger opens its menu, and you will often click the trigger you are pointing at a moment later, so a plain toggle would close the menu you had opened. I ignore a click that lands within 400 milliseconds of a hover opening the menu.

const clickTrigger = (id: MenuId) => {
  if (open === id && performance.now() - hoverOpenedAt < 400) return;
  setOpen(open === id ? null : id);
};

Keyboard support runs through the buttons. Each trigger has aria-expanded and aria-controls, so a screen reader announces whether its menu is open. You can Tab to a trigger and press Enter to open its menu, and with a menu open, moving focus to the next trigger switches the panel to it. Escape closes the menu from anywhere inside it.

That focus behaviour caused a bug on phones. A tap focuses the button before the click event fires, so my focus handler switched the menu first, and then the click handler found that menu already open and closed it. The panel started resizing toward the new menu and faded out halfway. The fix limits the focus switch to keyboard focus.

onFocus={(event) => {
  if (open === null) return;
  if (!event.currentTarget.matches(":focus-visible")) return;
  setOpen(id);
}}

The :focus-visible selector matches focus that came from the keyboard and skips focus from a tap or a mouse click, so on a phone the tap goes through the click handler alone.

Closing thoughts

The menu reads as one object because each moving part takes its position from the same two values. The open menu sets the panel and the links inside it, and your pointer sets the pill, so the parts can't drift out of step with each other.

Restricting the animation to properties that skip layout ruled out width, height and left, which pushed me toward clips for both the pill and the panel. The same clip that moves the pill also resizes the panel, and I rebuilt the border and the shadow so they would survive it.

The slide and the crossfade took a small amount of code. Most of the work went into the edge cases, the pointer crossing the row and the tap that fired two handlers, and those cases decide whether the menu feels calm or jumpy once it sits on a real page.