Skip to content

Instantly share code, notes, and snippets.

@Shwartz
Last active January 10, 2017 14:54
Show Gist options
  • Save Shwartz/17fcb0662568c994f09f2d8d2b91bcf9 to your computer and use it in GitHub Desktop.
Save Shwartz/17fcb0662568c994f09f2d8d2b91bcf9 to your computer and use it in GitHub Desktop.
JavaScript: Find element position by looping from element up to body tag
// Original source: https://www.kirupa.com/html5/get_element_position_using_javascript.htm
// Helper function to get an element's exact position
function getPosition(el) {
var xPos = 0;
var yPos = 0;
while (el) {
if (el.tagName == "BODY") {
// deal with browser quirks with body/window/document and page scroll
var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
var yScroll = el.scrollTop || document.documentElement.scrollTop;
xPos += (el.offsetLeft - xScroll + el.clientLeft);
yPos += (el.offsetTop - yScroll + el.clientTop);
} else {
// for all other non-BODY elements
xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
yPos += (el.offsetTop - el.scrollTop + el.clientTop);
}
el = el.offsetParent;
}
return {
x: xPos,
y: yPos
};
}
// deal with the page getting resized or scrolled
window.addEventListener("scroll", updatePosition, false);
window.addEventListener("resize", updatePosition, false);
function updatePosition() {
// add your code to update the position when your browser
// is resized or scrolled
var el = document.getElementById('testDistance');
console.log('update position: ', getPosition(el).y);
}
updatePosition(); // if you need to know on page load
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment