Get the position of an element relative to the document
Add the scroll offsets to the element’s viewport position.
function getPosition(element) { const rect = element.getBoundingClientRect(); return { left: rect.left + window.scrollX, top: rect.top + window.scrollY }; }
Usage
Markup
<div style="height: 1000px"></div>
<p id="target" style="margin: 0 0 0 40px">Target</p>
<div style="height: 2000px"></div>
Script
const target = document.querySelector('#target');
getPosition(target); // → { left: 40, top: 1000 }
window.scrollTo(0, 600);
getPosition(target); // → { left: 40, top: 1000 }
target.getBoundingClientRect().top; // → 400
Know the limits
- The original assigned to an undeclared r: a ReferenceError in strict mode and ES modules.
- getBoundingClientRect is relative to the viewport, as the last line shows; adding the scroll offsets gives document coordinates that stay put while scrolling.
- Transforms are included, and values are fractional when layout is.
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 Get the position of an element relative to the document from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Declares the rect variable; the original assigned to an undeclared r, which throws in strict mode and ES modules. 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.