Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Created Jun 18, 2018
Embed
What would you like to do?
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