Skip to content

Instantly share code, notes, and snippets.

@manuelcanga
Created January 7, 2022 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manuelcanga/2c8d72a36f2641ba6121c0688a90462f to your computer and use it in GitHub Desktop.
Save manuelcanga/2c8d72a36f2641ba6121c0688a90462f to your computer and use it in GitHub Desktop.
get position of an element in the web (js)
trasweb.getPosition = function (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