Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Created June 18, 2018 22:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrcoles/2ed727aec50423444930677ddebc1989 to your computer and use it in GitHub Desktop.
Save mrcoles/2ed727aec50423444930677ddebc1989 to your computer and use it in GitHub Desktop.
Compute the offset of a DOM element taking into account CSS transforms and scrolled parents.
export const computeOffset = elt => {
let rect = elt.getBoundingClientRect();
let width = rect.width;
let height = rect.height;
let left = 0;
let top = 0;
let offsetParent = elt;
while (offsetParent) {
left += offsetParent.offsetLeft;
// document.body sometimes has offsetTop == 0 but still has an
// offset because of children margins!
if (offsetParent === document.body) {
top += offsetParent.getBoundingClientRect().top + window.scrollY;
} else {
top += offsetParent.offsetTop;
}
let domMatrix = _domMatrix(offsetParent);
if (domMatrix) {
left += domMatrix.m41;
if (offsetParent !== document.body) {
top += domMatrix.m42;
}
}
offsetParent = offsetParent.offsetParent;
}
return { left, top, width, height };
};
// Compute the DOMMatrix transforms for this element
const _domMatrix = elt => {
if (window.DOMMatrix || window.WebKitCSSMatrix) {
let style = window.getComputedStyle(elt);
let trans = style.transform || style.webkitTransform;
return window.DOMMatrix
? new window.DOMMatrix(trans)
: new window.WebKitCSSMatrix(trans);
}
return undefined;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment