THE PASZ.COM BLOG

Friday, December 01, 2006

DHTML: IE Absolute Coordinates Hack

I found a handy IE hack. Since I couldn't find it anywhere on the net, I thought I'd post it.

The problem is that in IE 6, it's not possible to get the absolute (global) coordinates of an element, unless it's position property is set to "absolute". So if you have a relatively positioned element, IE does not give you a way to get it's position relative to the upper-left corner of the browser window. (In Firefox you can simply use the element.x and element.y properties.)

My solution was to use JavaScript to briefly switch the element's positioning to "absolute", grab the coordinates, and then immediately switch it back to relative.


var elementX = element.x;
var elementY = element.y;
if(!elementX){//hack for IE
   element.style.position = "absolute";
   elementX = element.offsetLeft;
   elementY = element.offsetTop;
   element.style.position = "relative";
}


This trick can be especially helpful if you're doing a liquid layout.