Finding the Absolute Position of an HTML Element (JavaScript)

Started by zourtney, Aug 22, 2009, 05:48 PM

Previous topic - Next topic

zourtney

Apparently finding the absolute position of an element of a webpage isn't as easy as you'd think. After a little digging, I came across some examples which accomplish this task by simply walking up the DOM tree. Not handy, but it is effective.


function findPosX( obj )
{
var curLeft = 0;

if ( obj.offsetParent != null )
{
while ( obj.offsetParent != null )
{
curLeft += obj.offsetLeft;
obj = obj.offsetParent;
}
}
else
{
curLeft += obj.x;
}

return curLeft;
}

function findPosY( obj )
{
var curTop = 0;

if ( obj.offsetParent != null )
{
while ( obj.offsetParent != null )
{
curTop += obj.offsetTop;
obj = obj.offsetParent;
}
}
else
{
curTop += obj.y;
}

return curTop;
}