demo · v137

Direction-aware Toolbar

The other half of v137: selection.direction. A floating toolbar that anchors to the start of the selection regardless of how you dragged. Drag forward → toolbar at left edge. Drag backward → toolbar still at the visual start. Holding shift and clicking past the anchor flips the direction back.

probing…
none 0 chars

The web platform has historically only let you read where the user started a selection (the anchor) and where it ended (the focus), but never which way around. That makes it surprisingly fiddly to decide where to put a contextual UI like a quote-tweet button or a translate popup.

Chrome 137 adds selection.direction, returning "forward", "backward", or "none". Now a tooltip can always sit at the visual start, regardless of drag direction. Try it: select forwards across this sentence, then drag backwards across the next paragraph.

This is the kind of thing screen-reader users and AT vendors have wanted for a long time — and was implementable already in Firefox/Safari but not portably. The Chrome 137 alignment closes the gap.

tip: select left-to-right vs right-to-left, then shift-click further out to flip direction without re-selecting.

selection.direction
selection.anchorNode/Offset
selection.focusNode/Offset
selected text (first 80 chars)

the code

document.addEventListener("selectionchange", () => {
  const sel = getSelection();
  const dir = sel.direction;  // NEW in v137
  // Whether the user dragged forward or backward, position the
  // toolbar at the actual visual start:
  const r = sel.rangeCount ? sel.getRangeAt(0) : null;
  if (!r || r.collapsed) return hideToolbar();
  const rects = r.getClientRects();
  const start = dir === "backward" ? rects[rects.length - 1] : rects[0];
  positionToolbar(start);
});

see also