Document Geometry and Scrolling: getBoundingClientRect, Viewport Coordinates, IntersectionObserver and ResizeObserver
Measure and move around the page: viewport vs document coordinates, CSS pixels and devicePixelRatio, getBoundingClientRect and getClientRects, elementFromPoint, scrollTo and scrollIntoView, offset, client and scroll sizes, and IntersectionObserver and ResizeObserver.
kvi5hnuCode Sprout team member8 min readOn this page
Tooltips, sticky headers, infinite scrolling, lazy loading and drag and drop all need to answer the same questions: where is this element, how big is it, and what's visible right now? This article covers the coordinate systems browsers use, the APIs that measure elements and scroll the page, and the observers that report geometry changes without polling.
Two coordinate systems
Positions are measured from one of two origins:
- Viewport coordinates are measured from the top-left corner of the visible window area. An element's viewport position changes whenever the page scrolls.
- Document coordinates are measured from the top-left corner of the whole document. They don't change on scroll.
The difference between them is the scroll offset:

const rect = element.getBoundingClientRect();
const documentTop = rect.top + window.scrollY; // viewport -> document
const documentLeft = rect.left + window.scrollX;
Mouse and pointer events report both: clientX/clientY in viewport coordinates and pageX/pageY in document coordinates. Most geometry APIs, including getBoundingClientRect(), elementFromPoint() and position: fixed, use viewport coordinates.
CSS pixels
The pixels in CSS and JavaScript are CSS pixels, not physical screen pixels. window.devicePixelRatio says how many device pixels make up one CSS pixel. It's 2 or 3 on most phones and high-resolution laptops, and it changes when the user zooms. It doesn't have to be a whole number, so coordinates like 10.5 are normal. It matters most when drawing on a <canvas>, which you size in device pixels to keep graphics sharp (article 115).
Measuring an element
element.getBoundingClientRect() returns a DOMRect with left, top, right, bottom, width, height (and x, y as aliases), in viewport coordinates:
const box = card.getBoundingClientRect();
console.log(box.top, box.left, box.width, box.height);
// position a tooltip just below the card, in document coordinates
tooltip.style.position = "absolute";
tooltip.style.left = `${box.left + window.scrollX}px`;
tooltip.style.top = `${box.bottom + window.scrollY + 8}px`;
The size includes padding and borders, but not margins, and it reflects CSS transforms. The result is a snapshot: it doesn't update when the page scrolls.
An inline element, such as a link that wraps across two lines, is made of several rectangles. getBoundingClientRect() returns one box that encloses them all, while getClientRects() returns each line's rectangle separately, which is useful for highlighting text precisely.
Which element is at a point?
The reverse question, "what is under this point?", is answered by document.elementFromPoint(x, y), using viewport coordinates. It returns the innermost, topmost element there, or null if the point is outside the viewport. document.elementsFromPoint(x, y) returns the whole stack, top to bottom:
document.addEventListener("pointermove", (event) => {
const under = document.elementFromPoint(event.clientX, event.clientY);
dropTarget = under?.closest(".drop-zone") ?? null;
});
Elements with pointer-events: none are skipped, which is how a dragged element can avoid finding itself.
Scrolling
The window scrolls with scrollTo (to an absolute document position) and scrollBy (relative to the current position). Both accept either (x, y) numbers or an options object, which allows smooth scrolling:
window.scrollTo(0, 0); // back to the top
window.scrollBy({ top: window.innerHeight * 0.8, behavior: "smooth" }); // about one screen down
window.scrollTo({ top: document.documentElement.scrollHeight, behavior: "smooth" }); // the bottom
More often you want a specific element to be visible. scrollIntoView scrolls every scrollable ancestor as needed:
errorField.scrollIntoView({ behavior: "smooth", block: "center" });
activeItem.scrollIntoView({ block: "nearest" }); // scroll only if it isn't already visible
block (vertical) and inline (horizontal) accept "start", "center", "end" or "nearest". With no argument, the element's top is aligned with the top of its scroll container. Scrollable elements have the same scrollTo, scrollBy and scrollTop/scrollLeft properties as the window.
In CSS, scroll-behavior: smooth makes all scrolling in a container smooth, and scroll-margin-top leaves room for a sticky header when an element is scrolled into view.
Viewport, content and scroll sizes
For the window:
| Property | Meaning |
|---|---|
window.innerWidth / innerHeight | viewport size, including any scrollbar |
document.documentElement.clientWidth / clientHeight | viewport size, excluding scrollbars |
document.documentElement.scrollHeight | full height of the document's content |
window.scrollX / scrollY | current scroll offsets (read-only: use scrollTo to change them) |
Every element has three families of size properties, all in whole CSS pixels:
| Property | Measures |
|---|---|
offsetWidth, offsetHeight | the rendered box: content + padding + border (+ scrollbar) |
offsetLeft, offsetTop, offsetParent | position relative to the nearest positioned ancestor (offsetParent) |
clientWidth, clientHeight | the inside: content + padding, without border or scrollbar |
clientLeft, clientTop | usually the border widths |
scrollWidth, scrollHeight | the full content size, including what's scrolled out of view |
scrollLeft, scrollTop | how far the content is scrolled (writable) |
These combine into common checks:
const hasOverflow = panel.scrollHeight > panel.clientHeight; // does it need a scrollbar?
const atBottom = panel.scrollTop + panel.clientHeight >= panel.scrollHeight - 1; // scrolled to the end?
const progress = window.scrollY / (document.documentElement.scrollHeight - innerHeight); // reading progress
The - 1 in atBottom allows for fractional scroll positions on high-density screens. Unlike getBoundingClientRect(), these properties are rounded to whole numbers and ignore transforms.
Reading any of these values forces the browser to bring the layout up to date. Article 111 explains why reads and writes should be batched separately.
Observers: react to geometry without polling
Older code listened to scroll and resize events and called getBoundingClientRect() on every one, which is slow and easy to get wrong. Modern browsers provide observers that compute geometry changes efficiently and call you only when something actually changes.
IntersectionObserver: is it visible?
IntersectionObserver reports when elements enter or leave the viewport, or any scrollable ancestor, which is called the root:
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const img = entry.target;
img.src = img.dataset.src; // lazy-load the real image
observer.unobserve(img); // done with this one
}
}, { rootMargin: "200px 0px" }); // start loading 200px before it scrolls into view
document.querySelectorAll("img[data-src]").forEach((img) => observer.observe(img));
Each entry has isIntersecting, intersectionRatio (0 to 1: how much is visible), boundingClientRect, intersectionRect and target. Options:
root: the scroll container to check against (the defaultnullmeans the viewport).rootMargin: grows or shrinks the root's box, in CSS margin syntax.threshold: a ratio or an array of ratios that trigger callbacks, such as[0, 0.5, 1].
The observer fires once for each element when you start observing it, with its current state.
Typical uses are lazy loading, infinite scrolling (observe a sentinel element at the end of a list and load more when it appears), playing videos only while they're visible, highlighting the current section in a table of contents, and counting ad impressions. For plain images, the HTML attribute loading="lazy" does lazy loading without any JavaScript.
ResizeObserver: did it change size?
window's resize event only reports viewport changes. Elements also resize when their content, their container or the font changes. ResizeObserver reports size changes of individual elements:
const sizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
const { inlineSize: width } = entry.contentBoxSize[0];
entry.target.classList.toggle("compact", width < 400);
redrawChart(entry.target, width);
}
});
sizeObserver.observe(chartContainer);
Each entry provides contentRect and the newer contentBoxSize/borderBoxSize arrays (with inlineSize and blockSize). For layout changes that depend only on a container's width, CSS container queries (@container (width < 400px)) can now do this without JavaScript; use ResizeObserver for logic like redrawing a canvas chart.
Call disconnect() on any observer when its component is removed, so the browser stops tracking those elements. MutationObserver, which reports DOM changes rather than geometry, follows the same pattern.
Common questions
getBoundingClientRect().width or offsetWidth?
getBoundingClientRect() gives fractional values and includes transforms (a scaled element reports its scaled size). offsetWidth is rounded and ignores transforms. Use getBoundingClientRect() for precise visual measurements.
Why is my element's top value different every time I check it?
getBoundingClientRect() uses viewport coordinates, which change as the page scrolls. Add window.scrollY to get a stable document position.
How do I detect when the user scrolls near the bottom of a list?
Put a small sentinel element after the last item and observe it with an IntersectionObserver (with a rootMargin to load early). When it intersects, fetch more items. This avoids running code on every scroll event.
Is there a way to check if an element is visible right now, without an observer?
Compare its rect with the viewport: rect.bottom > 0 && rect.top < innerHeight && rect.right > 0 && rect.left < innerWidth. Newer browsers also offer element.checkVisibility(), which tests CSS visibility (for example, display: none or content-visibility) rather than scroll position.
Summary
- Viewport coordinates change with scrolling; document coordinates don't. Document = viewport +
scrollX/scrollY. Events giveclientX/clientY(viewport) andpageX/pageY(document). getBoundingClientRect()returns an element's fractional, transformed box in viewport coordinates;getClientRects()returns the separate boxes of wrapped inline content;elementFromPoint()finds what's under a point.- Scroll with
scrollTo,scrollByandscrollIntoView({ behavior, block }). offset*is the rendered box,client*is the inner area andscroll*is the full content and scroll position.IntersectionObserverreports visibility changes (lazy loading, infinite scrolling);ResizeObserverreports element size changes. Both replace polling inscrollandresizehandlers.
Practice Questions
A button is 300px from the top of the viewport, and the page is scrolled down 1200px. What are its viewport and document top values?
Answer
Viewport: 300 (from getBoundingClientRect().top). Document: 300 + 1200 = 1500.
Write a check that says whether a scrollable div#log is scrolled all the way to the bottom.
Answer
const atBottom = log.scrollTop + log.clientHeight >= log.scrollHeight - 1;
scrollHeight is the full content height, clientHeight the visible part, and scrollTop how far it's scrolled. The - 1 tolerates fractional scroll positions.
Replace this scroll handler with an observer.
window.addEventListener("scroll", () => {
const r = footer.getBoundingClientRect();
if (r.top < innerHeight) loadMore();
});
Answer
new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) loadMore();
}).observe(footer);
The callback runs only when the footer enters or leaves the viewport, not on every scroll event, and the browser computes the intersection efficiently.
How do you scroll a form error into view smoothly, centered on screen?
Answer
field.scrollIntoView({ behavior: "smooth", block: "center" });
field.focus({ preventScroll: true });
preventScroll stops focus() from jumping the page again before the smooth scroll finishes.
Next: Web Components: Custom Elements, Shadow DOM, Templates and Slots

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.