Last active
November 12, 2017 15:13
-
-
Save aderaaij/fd37b6569fffc77251600028d59d44b9 to your computer and use it in GitHub Desktop.
Get an elements X and Y position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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