Skip to content

Instantly share code, notes, and snippets.

@bradmarshall
Last active September 25, 2016 15:29
Show Gist options
  • Save bradmarshall/8f3e6f8a0e93b2dafef307232afbedc2 to your computer and use it in GitHub Desktop.
Save bradmarshall/8f3e6f8a0e93b2dafef307232afbedc2 to your computer and use it in GitHub Desktop.
A simple little function to get the position of an element with respect to the upper top left of the viewport. Uses getBoundingClientRect() for today's browsers and falls back to an older method for older browsers.
// Get position of element from top of viewport.
function getPosition(element) {
// Modern browsers.
if(element.getBoundingClientRect) {
var clientRect = element.getBoundingClientRect();
return {
x: Math.floor(clientRect.left),
y: Math.floor(clientRect.top)
};
}
// Old browsers.
var xPosition = 0;
var yPosition = 0;
while(element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment