Here we use the ES6 method, which returns all the same properties as getBoundingClientRect() , but relative to the entire document.
const getOffsetRect = (el) => let rect = el.getBoundingClientRect(); // add window scroll position to get the offset position let left = rect.left + window.scrollX; let top = rect.top + window.scrollY; let right = rect.right + window.scrollX; let bottom = rect.bottom + window.scrollY; // polyfill missing 'x' and 'y' rect properties not returned // from getBoundingClientRect() by older browsers if ( rect.x === undefined ) let x = left; else let x = rect.x + window.scrollX; if ( rect.y === undefined ) let y = top; else let y = rect.y + window.scrollY; // width and height are the same let width = rect.width; let height = rect.height; return { left, top, right, bottom, x, y, width, height }; };
Note: it also polyfills the details x and y , which are not returned from getBoundingClientRect () by older browsers
source share