Thursday, April 15, 2010

Find X and Y coordinate of HTML control - amendsoft

Find X and Y coordinate of HTML control

The main purpose of these two functions given below is to find the absolute positions of a HTML controls measured in it X and Y coordinates. These functions work perfectly in both IE and Firefox.

Below is the code.

Find X position of HTML control

function findPositionX(obj)
{
    var left = 0;
    if(obj.offsetParent)
    {
        while(1) 
        {
          left += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    }
    else if(obj.x)
    {
        left += obj.x;
    }
    return left;
}
 
Find Y position of HTML control
 
function findPosY(obj)
{
    var top = 0;
    if(obj.offsetParent)
    {
        while(1)
        {
          top += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    }
    else if(obj.y)
    {
        top += obj.y;
    }
    return top;
  }

If you find this post beneficial, the please post a comment on it.

Manu Singh
AmendSoft
info@amendsoft

6 comments:

  1. You swiped this almost verbatim from here: http://blog.firetree.net/2005/07/04/javascript-find-position/

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thanks. "obj.offsetLeft" is very useful...

    ReplyDelete