Created
March 27, 2021 19:17
-
-
Save niklasp/1213e285befecf4c3b23285a359a786d to your computer and use it in GitHub Desktop.
Get the exact position of an element
This file contains 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
// 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 | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment