Skip to content

Instantly share code, notes, and snippets.

@niklasp
Created March 27, 2021 19:17
Show Gist options
  • Save niklasp/1213e285befecf4c3b23285a359a786d to your computer and use it in GitHub Desktop.
Save niklasp/1213e285befecf4c3b23285a359a786d to your computer and use it in GitHub Desktop.
Get the exact position of an element
// 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