In view
Find out which elements of a scrolling container are completely visible.
Demo
Try this: Scroll the box, or click it and use the arrow keys. A grey box that is completely visible turns yellow and says so. A box that is cut off at the top or bottom edge stays grey.
Calculated values
How it works
- Every box is an item with its own calculator, and the scrolling container is the boundary. There is no target: the library only checks the box against the boundary.
-
calculate()returnsdistance.overflow, the list of edges the box overflows, ornullif it overflows none. A box without overflow is completely visible. -
Without a target and without
stick, nothing moves the box. The example ignoresmoveByand only readsdistance. -
The container's
scrollevent calls the update, because a calculation is not automatic: it runs when you callcalculate(). The call also reads the current positions, so scrolling needs noresize(). The example calls it once at the start for the first state. - The container has
tabindex="0", so keyboard users can scroll it with the arrow keys.
Variations
-
In the playground, replace
!overflowwith!overflow?.includes("bottom"): a box that is cut off only at the top then counts as in view. -
Use the window as the boundary (
boundary: "window") to react to the scrolling of the whole page. Then listen to thescrollevent ofwindow.