Thursday, September 25, 2008

Calculating absolute position

// here is a Javascript routine that calculates the absolute position of an html
// element by recursively traversing the parent dom elements
// (works in IE, Firefox, Safari , etc.)

Map.Drawing.Point.prototype.addAbsolutePosition = function(obj) {
var X, Y;
var cur;
if (!obj) {
return this;
}
else
{
X=parseInt("0" + this.x);
Y=parseInt("0" + this.y);
var o = obj;
if (o.offsetParent) //then this object has a container that affects its position
{
while (o.offsetParent)
{
X += parseInt(o.offsetLeft);
Y += parseInt(o.offsetTop);
o = o.offsetParent; //traverse the hierarchy upward
}
}
else if (o.x || o.y) //no container but an absolute position
{
if (o.x) X += parseInt(o.x);
if (o.y) Y += parseInt(o.y);
}

this.x = X;
this.y = Y;

return this;
}
};

No comments: