Calculate the distance to the bottom of a page
Pixels left to scroll before the end of the page.
function distanceToBottom() { return document.documentElement.scrollHeight - window.innerHeight - window.scrollY; }
Usage
Markup
<div style="height: 3000px">A 3000 px tall page</div>
Script
// A 3000 px tall page in a 720 px tall viewport:
distanceToBottom(); // → 2280
window.scrollTo(0, 280);
distanceToBottom(); // → 2000
Know the limits
- document.documentElement.scrollHeight measures the whole page. The original used document.body.scrollHeight, which can differ when body has margins or a fixed height.
- Scroll positions can be fractional on zoomed or high-density screens: compare with a 1 px tolerance.
- For infinite scrolling, an IntersectionObserver on a sentinel element avoids measuring on every scroll event.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Calculate the distance to the bottom of a page from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
A function measuring document.documentElement instead of a value from document.body. Executed in Chromium. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.