Retrieve the position (X,Y) of an HTML element relative to the browser window Retrieve the position (X,Y) of an HTML element relative to the browser window javascript javascript

Retrieve the position (X,Y) of an HTML element relative to the browser window


The correct approach is to use element.getBoundingClientRect():

var rect = element.getBoundingClientRect();console.log(rect.top, rect.right, rect.bottom, rect.left);

Internet Explorer has supported this since as long as you are likely to care about and it was finally standardized in CSSOM Views. All other browsers adopted it a long time ago.

Some browsers also return height and width properties, though this is non-standard. If you're worried about older browser compatibility, check this answer's revisions for an optimised degrading implementation.

The values returned by element.getBoundingClientRect() are relative to the viewport. If you need it relative to another element, simply subtract one rectangle from the other:

var bodyRect = document.body.getBoundingClientRect(),    elemRect = element.getBoundingClientRect(),    offset   = elemRect.top - bodyRect.top;alert('Element is ' + offset + ' vertical pixels from <body>');


The libraries go to some lengths to get accurate offsets for an element.
here's a simple function that does the job in every circumstances that I've tried.

function getOffset( el ) {    var _x = 0;    var _y = 0;    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {        _x += el.offsetLeft - el.scrollLeft;        _y += el.offsetTop - el.scrollTop;        el = el.offsetParent;    }    return { top: _y, left: _x };}var x = getOffset( document.getElementById('yourElId') ).left; 


This function returns an element's position relative to the whole document (page):

function getOffset(el) {  const rect = el.getBoundingClientRect();  return {    left: rect.left + window.scrollX,    top: rect.top + window.scrollY  };}

Using this we can get the X position:

getOffset(element).left

... or the Y position:

getOffset(element).top

TypeScript version:

export type ElementOffset = {  left: number;  top: number};/** * Returns an element's position relative to the whole document (page). * * If the element does not exist, returns O/O (top-left window corner). * * @example getOffset(document.getElementById('#element')); * * @param el * @see https://stackoverflow.com/a/28222246/2391795 */export const getElementOffset = (el: Element | null): ElementOffset => {  const rect = el?.getBoundingClientRect();  return {    left: (rect?.left || 0) + window?.scrollX,    top: (rect?.top || 0) + window?.scrollY,  };};export default getElementOffset;