Created
September 5, 2016 10:26
-
-
Save LiamChapman/386cd0702e9fe760250854966b0d09f7 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
this is the most awesome hacking method I've found. thanks.