Skip to content

Instantly share code, notes, and snippets.

@williammalo
Forked from 140bytes/LICENSE.txt
Last active October 6, 2015 14:18
Show Gist options
  • Select an option

  • Save williammalo/3005883 to your computer and use it in GitHub Desktop.

Select an option

Save williammalo/3005883 to your computer and use it in GitHub Desktop.
get offset of element

recursively checks every parent of the element to get the ABSOLUTE offset of the element.

call it like this:

getOff(element);
getOff(element);
function(a,x,y){
for(x=y=0;a;a=a.offsetParent) //Loop through element and all it's parents
x+=a.offsetLeft, //add offset of current element to variables x and y
y+=a.offsetTop;
return{x:x,y:y} //return object of x and y
}
function(a,x,y){for(x=y=0;a;a=a.offsetParent)x+=a.offsetLeft,y+=a.offsetTop;return{x:x,y:y}}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "getOff",
"description": "returns the ABSOLUTE offset of an element",
"keywords": [
"css",
"position",
"offset",
"absolute"
]
}
<!doctype html>
<style>
#foo{position:relative;top:100px;margin:40px}​
</style>
<div id=foo></div>
<script>
getOff = function(a,x,y){for(x=y=0;a;a=a.offsetParent)x+=a.offsetLeft,y+=a.offsetTop;return{x:x,y:y}};
document.write(
getOff(document.getElementById("foo")).y
);
</script>
@atk
Copy link

atk commented Jun 28, 2012

Why not both in one function?

function(a,x,y){for(x=y=0;a;a=a.offsetParent)x+=(a.offsetLeft||0),y+=(a.offsetTop||0);return{left:x,top:y}}

Anyway, the offset method is not very precise in some browsers (especially in Quirks mode). A better way to go (if available) is to use getBoundingClientRect, though this results in relative positions to the visible browser window.

@williammalo
Copy link
Author

@atk
:D I made it one function that returns an object. Thanks for the Idea!
I originally did this as part of a "smooth scrolling to hashlink" script.
... I could make it a prototype and the function would be hidden in a getter, so you could do:

document.getElementById("foo").x
document.getElementById("foo").y

it would be a much simpler syntax but the code would be longer...

@atk
Copy link

atk commented Jun 28, 2012

This reminds me too much of the ambigious old actionscript syntax... I'll rather take the object, thanks.

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