Skip to content

Instantly share code, notes, and snippets.

@AeonFr
Created April 19, 2018 16:30
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 AeonFr/7d333a51cce958e5729d3105aab4a0e8 to your computer and use it in GitHub Desktop.
Save AeonFr/7d333a51cce958e5729d3105aab4a0e8 to your computer and use it in GitHub Desktop.
calculateTotalOffsetTop() & calculateTotalOffsetLeft() - Recursive totalOffset of an $element, to calculate it's position relative to the whole page.
function calculateTotalOffsetTop (elem, total){
total = total || 0;
total = elem.offsetTop + total;
if (elem.offsetParent) return calculateTotalOffsetTop(elem.offsetParent, total)
else return total;
}
function calculateTotalOffsetLeft (elem, total){
total = total || 0;
total = elem.offsetLeft + total;
if (elem.offsetParent) return calculateTotalOffsetLeft(elem.offsetParent, total)
else return total;
}
@AeonFr
Copy link
Author

AeonFr commented Apr 19, 2018

⭐ Usage:
var $selector = document.querySelector('#myDiv')
calculateTotalOffsetTop($selector)

Please notice:

  • The second parameter of the functions is "for internal use". No need to put anything (or just put zero).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment