Attack Work TMBeta
Productivity tools to accomplish work faster
 
Username Password
   
Password help
Create new account
Skip Navigation Links.

Javascript - Object Position (Top and Left Offset) on a Page

Steal This Site [Web Developer Blog]


Retrieves the left and top offset of an object using Javascript. I got this from Peter-Paul Koch's page http://www.quirksmode.org/js/findpos.html. His description is more extensive.

Code:
function ObjectPosition(obj) {
    var curleft = 0;
      var curtop = 0;
      if (obj.offsetParent) {
            do {
                  curleft += obj.offsetLeft;
                  curtop += obj.offsetTop;
            } while (obj = obj.offsetParent);
      }
      return [curleft,curtop];
}

Pass in the object you'd like the position of and it'll return a 2 item array. The first item is the left offset and the second item is the top offset.

Javascript only lets us check the offset from the object's parent. Since the object may be nested inside other elements, each of the parent's offsets must be added to get the final offset result.

The example below shows how to get the offset of an element called MyElementId. Place the code at the bottom of the BODY tag and right above </body>.

Code:
<div id="MyElementId">My test element</div>
<script language="javascript" type="text/javascript">
var aryPosition = ObjectPosition(document.getElementById('MyElementId'));
document.write('MyElementId left offset is ' + aryPosition[0] + '<br />');
document.write('MyElementId top offset is ' + aryPosition[1] + '<br />');
</script>

Subscribe in a reader
Michael Khalili | Thursday, September 25, 2008
Comments
All guest comments are moderated.
Be the first to comment on this post
Post your comment
Guest Name* !
Email Address* !(Not published)
Website !
Comment*
!
*Required fields


Terms of Service | Privacy Policy | Steal This Site
Attack Work and Voxback are trademarks of Hillside Holdings.