Element coordinates

Did you ever need HTML Elements absolute position / coordinates ? I coded one function for this purpose a while ago and I consider it very useful and handy.

The code


It is a JavaScript function of course, here's the code:

function GetAbsPos(elem)
{
    var end  = false;
    var prnt = elem;
    var x    = 0;
    var y    = 0;
 
    while (!end)
    {
        if (prnt != null)
        {
            if (prnt.offsetLeft)
            {
                x += prnt.offsetLeft;
            }
 
            if (prnt.offsetTop)
            {
                y  += prnt.offsetTop;
            }
 
            prnt = prnt.offsetParent;
        }
        else
        {
            break;
        }
    }//while
 
    return {Left: x, Top: y};
}//GetAbsPos


It returns an object with attributes - Left and Top. Here's an example of how you can use it.

var pos  = GetAbsPos(elem);
 
alert(pos.Left + ',' + pos.Top);


This function works perfectly on all browsers (IE, FFX, Opera, Chrome).

Njoy ;)