There are many times that I want to absolutely position something, but in a relative position to something else on the page. Ergo, I need to find the top and left px value for an element I'll use as the "anchor" - but based on the way the DOM tree is laid out, I need to add together the offsets of all the parent nodes that "own" me to get the right values. Here is the code I use.
[ I'll be using this code in my Argument Against Ajax post as well... ]
Note that this expects you to pass a reference to a node, so you might use it like this:
var myElement = document.getElementById('myElement');
var top = getElementTop(myElement);
function getElementLeft(obj)
{
var curleft = 0;
if(obj.offsetParent)
{
while(true)
{
curleft += obj.offsetLeft;
if(!obj.offsetParent) { break; }
obj = obj.offsetParent;
}
} else if(obj.x) { curleft += obj.x; }
return curleft;
}
function getElementTop(obj)
{
var curtop = 0;
if(obj.offsetParent)
{
while(true)
{
curtop += obj.offsetTop;
if(!obj.offsetParent) { break; }
obj = obj.offsetParent;
}
} else if(obj.y) { curtop += obj.y; }
return curtop;
}