Position a tooltip inside the viewport
This is the core of every popover library. You know where the trigger is and how big the tooltip is; you need coordinates that keep the tooltip on screen. Real code measures with getBoundingClientRect(), but the placement decision itself is pure arithmetic over those numbers.
Implement placeTooltip(anchor, tooltip, viewport, gap = 8). anchor is { x, y, width, height } in viewport coordinates, tooltip is { width, height }, and viewport is { width, height }. Return { x, y, placement }.
Vertically, prefer above: y = anchor.y - tooltip.height - gap, with placement of "top". If that y is less than 0 there is no room, so flip below with y = anchor.y + anchor.height + gap and placement of "bottom". The flipped position is not clamped further — if it also overflows, it stays below.
Horizontally, centre on the anchor: x = anchor.x + anchor.width / 2 - tooltip.width / 2, then clamp into the range 0 to viewport.width - tooltip.width. If the tooltip is wider than the viewport that range is empty, so use x = 0. Both returned coordinates are rounded with Math.round.
What it has to do
- Return
{ x, y, placement }withplacementbeing"top"or"bottom". - Place the tooltip
gappixels above the anchor when there is room, defaultinggapto 8. - Flip below the anchor when the top position would be above 0.
- Centre horizontally on the anchor, then clamp into
0 .. viewport.width - tooltip.width. - Use
x = 0when the tooltip is wider than the viewport, and round both coordinates withMath.round.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.