Skip to content

Instantly share code, notes, and snippets.

@LiamChapman
Created September 5, 2016 10:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LiamChapman/386cd0702e9fe760250854966b0d09f7 to your computer and use it in GitHub Desktop.
Save LiamChapman/386cd0702e9fe760250854966b0d09f7 to your computer and use it in GitHub Desktop.
Absolute Position of Element in Javascript
if (typeof absolutePosition == "undefined") {
// Discovered here: http://stackoverflow.com/a/32623832/867154
// Many thanks to @RoboCat!
function absolutePosition (el) {
var found, left = 0, top = 0, width = 0, height = 0, offsetBase = absolutePosition.offsetBase;
if (!offsetBase && document.body) {
offsetBase = absolutePosition.offsetBase = document.createElement('div');
offsetBase.style.cssText = 'position:absolute;left:0;top:0';
document.body.appendChild(offsetBase);
}
if (el && el.ownerDocument === document && 'getBoundingClientRect' in el && offsetBase) {
var boundingRect = el.getBoundingClientRect();
var baseRect = offsetBase.getBoundingClientRect();
found = true;
left = boundingRect.left - baseRect.left;
top = boundingRect.top - baseRect.top;
width = boundingRect.right - boundingRect.left;
height = boundingRect.bottom - boundingRect.top;
}
return {
found: found,
left: left,
top: top,
width: width,
height: height,
right: left + width,
bottom: top + height
};
}
}
@ttys3
Copy link

ttys3 commented Mar 10, 2020

this is the most awesome hacking method I've found. thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment