Created
January 7, 2022 19:27
-
-
Save manuelcanga/2c8d72a36f2641ba6121c0688a90462f to your computer and use it in GitHub Desktop.
get position of an element in the web (js)
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
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