Created
June 18, 2018 22:27
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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