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;
}

  • monk

    Thats it. I was getting worried, because I could not figure out why this stopped working in firefox. Figured out that it was something to do with Doctype but got stuck there. This worked perfectly.

comments powered by Disqus