Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Created December 20, 2011 04:37
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 jonathantneal/1500278 to your computer and use it in GitHub Desktop.
Save jonathantneal/1500278 to your computer and use it in GitHub Desktop.
getElementOffset.js
function getElementOffset(el)
{
for (var offsetTop = 0, offsetLeft = 0; el.offsetParent; el = el.parentNode)
{
offsetTop += el.offsetTop;
offsetLeft += el.offsetLeft;
}
return {
offsetTop: offsetTop,
offsetLeft: offsetLeft
};
}
// gf3 style
function getElementOffset(el) {
var offsetTop = 0, offsetLeft = 0;
if (el.offsetParent)
{
do {
offsetTop += el.offsetTop;
offsetLeft += el.offsetLeft;
} while (el = el.offsetParent);
}
return {
offsetTop: offsetTop,
offsetLeft: offsetLeft
};
}
@gf3
Copy link

gf3 commented Dec 20, 2011

Here's my version:

function offset ( el ) {
  var left = 0, top = 0
  if ( el.offsetParent )
    do {
      left += el.offsetLeft
      top  += el.offsetTop
    } while ( el = el.offsetParent )
  return { 0: left, 1: top, left: left, top: top, length: 2 }
}

@jonathantneal
Copy link
Author

Great ideas, @gf3, and I think it could be smaller too.

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