...

View Full Version : offsetLeft offsetTop returning 1



rlemon
04-18-2005, 03:24 PM
Hey,
I need to find the top, left offset of a Div Tag that exists within a table.

Example of the div in table:



<center><br><br>
<table border="1">
<tr>
<td><div id="Layer1">test</div></td>
</tr>
<table>
</center>


using document.getElementById('Layer1').offsetLeft

i return "1" always

rlemon
04-18-2005, 05:04 PM
figured it out.

i need to set position: relative; in the div style.
then use document.getElementById('id').offsetLeft

Kor
04-19-2005, 08:36 AM
The offsetLeft and offsetTop are relative to the parent. To find out the absolute real position of an object you have to loop to all the parents, if exists



function findPos(obj){//gets the absolute position of the objects
var x = obj.offsetLeft;var y = obj.offsetTop;
while(obj.offsetParent){
if(obj==document.getElementsByTagName('body')[0]){break;}
else{
x=x+obj.offsetParent.offsetLeft;
y=y+obj.offsetParent.offsetTop;
obj=obj.offsetParent;
}
}
this.x=x;this.y=y;
return this.x;
return this.y;
}


In the particular case of a table centered with HTML attribute, it is better to use <tbody> as an abject instead of <table> (otherwise Mozilla will return left 0)

On the other hand it is useful to have always defined margins for body, to avoid differences in different browsers.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum