Last active
August 9, 2017 12:58
-
-
Save pocketjoso/6f3f5483226e12fb3f6c21c239d9e121 to your computer and use it in GitHub Desktop.
getElementOffset in JavaScript
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
// calcule the offset in pixels to top of the site, | |
// from a DOM element (el) | |
export default function getElementOffset(el) { | |
let top = 0 | |
let left = 0 | |
// grab the offset of the element relative to it's parent, | |
// then repeat with the parent relative to it's parent, | |
// ... until we reach an element without parents. | |
do { | |
top += el.offsetTop | |
left += el.offsetLeft | |
el = el.offsetParent | |
} while (el) | |
return { top, left } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment