Skip to content

Instantly share code, notes, and snippets.

@ttys3
Forked from LiamChapman/absolutePosition.js
Created March 10, 2020 12:18
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 ttys3/c5267928480a6bbc6decd8a47e6a0ce1 to your computer and use it in GitHub Desktop.
Save ttys3/c5267928480a6bbc6decd8a47e6a0ce1 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
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment