Skip to content

Instantly share code, notes, and snippets.

@bidiu
Last active April 4, 2019 02:26
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 bidiu/d0c2ec220dacab3ba077b139f6ba2c9b to your computer and use it in GitHub Desktop.
Save bidiu/d0c2ec220dacab3ba077b139f6ba2c9b to your computer and use it in GitHub Desktop.
Calculate the distance of a give HTML element to viewport
// could be replaced by getBoundingClientRect()
function getDistanceToViewport(element: HTMLElement) {
let left = 0, top = 0, current: HTMLElement
current = element
while (current) {
left += current.offsetLeft
top += current.offsetTop
current = current.offsetParent as HTMLElement
}
let scrollLeft = 0, scrollTop = 0;
current = element
while (current) {
scrollLeft += current.scrollLeft
scrollTop += current.scrollTop
current = current.parentElement
}
left -= scrollLeft
top -= scrollTop
return { left, top }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment