Sep 04 2008
Calculating x and y coordinates of an element in JavaScript
I was trying to get the Swazz calendar to work on Firefox but it would get displayed at the top on the webpage instead of showing up just under the textbox element which required the calendar values. So while debugging it i noticed that i had the the Transitional DocType on and it was messing around with it. I googled the problem and found that the solution was to ‘px’ to the value otherwise Firefox would ignore it.
getObj(’fc’).style.left=Left(ielem) + ‘px’;
getObj(’fc’).style.top=Top(ielem)+ielem.offsetHeight + ‘px’;
And this is how you get the coordinates with JavaScript:
function Left(obj)
{
var curleft = 0;
if (obj.offsetParent)
while (1) {
curleft += obj.offsetLeft;
if (!obj.offsetParent)
break;
obj = obj.offsetParent;
}
else if (obj.x)
curleft += obj.x;
return curleft;
}
function Top(obj)
{
var curtop = 0;
if (obj.offsetParent)
while (1) {
curtop += obj.offsetTop;
if (!obj.offsetParent)
break;
obj = obj.offsetParent;
}
else if (obj.y)
curtop += obj.y;
return curtop;
}