Skip to content

Instantly share code, notes, and snippets.

@elrumordelaluz
Created August 29, 2014 13:14
Show Gist options
  • Save elrumordelaluz/2736b871a7607d7f81f8 to your computer and use it in GitHub Desktop.
Save elrumordelaluz/2736b871a7607d7f81f8 to your computer and use it in GitHub Desktop.
getOffsetRect()
function getOffsetRect(elem) {
// Get the enclosing elem.
var box = elem.getBoundingClientRect()
var body = document.body
var docElem = document.documentElement
// Calculate the page scroll. All browsers except IE<9 support `pageXOffset/pageYOffset`, and in IE when DOCTYPE is set, the scroll can be taken from documentElement(<html>), otherwise from `body` - so we take what we can.
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft
// The document (`html` or `body`) can be shifted from left-upper corner in IE. Get the shift.
var clientTop = docElem.clientTop || body.clientTop || 0
var clientLeft = docElem.clientLeft || body.clientLeft || 0
// Add scrolls to window-relative coordinates and substract the shift of `html/body` to get coordinates in the whole document.
var top = box.top + scrollTop - clientTop
var left = box.left + scrollLeft - clientLeft
return { top: Math.round(top), left: Math.round(left) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment