Skip to content

Instantly share code, notes, and snippets.

@aderaaij
Last active November 12, 2017 15:13
Show Gist options
  • Save aderaaij/fd37b6569fffc77251600028d59d44b9 to your computer and use it in GitHub Desktop.
Save aderaaij/fd37b6569fffc77251600028d59d44b9 to your computer and use it in GitHub Desktop.
Get an elements X and Y position
function getPosition(el) {
let xPos = 0;
let yPos = 0;
while (el) {
if (el.tagName == 'BODY') {
// deal with browser quirks with body/window/document and page scroll
const xScroll = el.scrollLeft || document.documentElement.scrollLeft;
const 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,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment