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
function(){
/* Rules: // make sure
(1) anonymous function // to annotate
(2) optionally self-executing // your code
(3) <140 bytes // so everyone
(4) no global vars // can learn
(5) MIT license // from it!
(6) good luck!
*/}
function(){/*Rules: (1) anonymous function (2) optionally self-executing (3) <140 bytes (4) no global vars (5) MIT license (6) good luck!*/}
Copyright (c) 2011 YOUR_NAME_HERE, YOUR_URL_HERE
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"name": "sample",
"keywords": [ "sample", "original" ]
}
@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