Object Position (Top and Left Offset) on a Page

by michaelkhalili on September 27, 2009

Retrieves the left and top offset of an object using Javascript. I got this from Peter-Paul Koch. His description is more extensive.

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>.

<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>
  • MTR

    Excellent

  • Hiral Amodia

    Thanks a lot. This small snip of code actually helped a lot to me.

  • Chetan

    I have been searching the google for last 1 week… finally i got it on your site.. thanx a lot ;)

  • Guest

    This is Good thanks a lot for sharing…

  • Nalddon

    Hi,

    nice trick. However, i have a little problem. For the BODY tag, I always get 0,0 back. Why does that happen? Any idea?

    • http://MichaelApproved.com/ MichaelApproved

      It’s the placement within the browser, not the screen. Having a body of 0,0 makes sense since the body is essentially the entire page.

  • Darkdangel

    Great Tip!

  • Krishna Kumar

    nice post….

  • Rakeshfrom1985

    Its usefull for me.Thanks

Previous post:

Next post: