View Full Version : Get the absolute position of elements in the DOM

05-14-2006, 03:15 AM
I have some div tags that I want to capture the xy coordinates using javascript. It seems that if I do not preset the absolute positioning values I cannot access them.

For example I have a div tag nested in a table:

<td width="400">some other code</td>
<td width="380">
<div Id="DivId">div content</div>

You will notice the positioning of the div tag is drive by the table it is nested in. The value of document.getElementById('DivId').style.left and document.getElementById('DivId').style.right is null. It sems I can only get these values of they are preset.

If someone could enlighten me with the solution I would be greate appreciative.

05-14-2006, 03:38 AM
Read these:

05-14-2006, 06:25 PM
I should add that you must probably consider the scroll position as well...

05-20-2006, 08:22 AM
function whereAmI(who,wch){
var L=0, R=0;
var pa=who;
L+= ( pa.offsetLeft)? pa.offsetLeft: 0;
R+= (pa.offsetTop)? pa.offsetTop: 0;

if(pa==document.body || wch===false)break;
pa= pa.parentNode;

var A=[L,R];
return(wch===1 || wch=== 2)? A[wch]: A;
This returns the left and top coordinates of the element sent
as the first argument. If the second argumentis a literal false,
it returns the position relative to its parent, otherwise it returns the
position relative to the body (includes the body offsets as well).

You can send an integer (1 or 2) if you just want the
first(left) or second(right) coordinate.