Skip to content

Instantly share code, notes, and snippets.

@pocketjoso
Last active August 9, 2017 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pocketjoso/6f3f5483226e12fb3f6c21c239d9e121 to your computer and use it in GitHub Desktop.
Save pocketjoso/6f3f5483226e12fb3f6c21c239d9e121 to your computer and use it in GitHub Desktop.
getElementOffset in JavaScript
// 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