How to retrieve the position (X,Y) of an HTML element in JavaScript ?

To retrieve the absolute position (X, Y coordinates) of an HTML element relative to the document or viewport in JavaScript, use the getBoundingClientRect() method combined with window.scrollX and window.scrollY. Here’s how:

1. Get Position Relative to the Viewport

The viewport is the visible area of the browser window.

const element = document.querySelector("#yourElementId");
const rect = element.getBoundingClientRect();

// Viewport-relative coordinates
const viewportX = rect.left;  // X from left edge of viewport
const viewportY = rect.top;   // Y from top edge of viewport

2. Get Position Relative to the Document

The document includes the entire page (even scrolled-out areas).

// Adjust for scrolling to get absolute document position
const documentX = rect.left + window.scrollX;
const documentY = rect.top + window.scrollY;

3. Full Example

const element = document.getElementById("myElement");
const rect = element.getBoundingClientRect();

// Absolute position in the document
const absoluteX = Math.round(rect.left + window.scrollX);
const absoluteY = Math.round(rect.top + window.scrollY);

console.log(`X: ${absoluteX}px, Y: ${absoluteY}px`);

Key Notes

  • getBoundingClientRect(): Returns an object with properties:
  • left, right, top, bottom, width, height.
  • window.scrollX/window.scrollY: The current horizontal/vertical scroll offset of the document.
  • Rounding: Use Math.round() to avoid fractional pixel values (optional).

Alternative: offsetLeft and offsetTop

These properties return the position relative to the offset parent (nearest positioned ancestor):

const x = element.offsetLeft;  // X relative to offset parent
const y = element.offsetTop;   // Y relative to offset parent


Limitations:

  • Does not account for scrolling.
  • Position depends on the element’s parent layout (e.g., position: relative).

When to Use Which

  • getBoundingClientRect(): Best for most use cases (accurate viewport/document positions).
  • offsetLeft/offsetTop: Use if you need positions relative to a parent container.

Example Output

For an element 100px from the left and 200px from the top of the document (with no scrolling):

absoluteX = 100, absoluteY = 200


If the user has scrolled 50px down:

absoluteY = 200 + 50 (scrollY) = 250

Leave a Reply

Your email address will not be published. Required fields are marked *