-
-
Save ttys3/c5267928480a6bbc6decd8a47e6a0ce1 to your computer and use it in GitHub Desktop.
Absolute Position of Element in Javascript
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
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