View Full Version : Getting the absolute position of an a element

12-20-2002, 08:50 PM
I have a valid XHTML 1 transitional page with the folowing elements:
<div><div><a href="">text</a></div></div>
I have some CSS associated with the elements,but I didn't set the position property nor the top/left properties for the elements.How can I get the absolute position (i.e. the distance from html element to the a element) of the a element (in a W3C standard compliant way,so that it will work in Mozilla and Konqueror)?
I have a absolute positioned div which I want to move to near the link,but I can't get it's absolute position.
Btw.I tried computed style,but it returns NaN (not a number) because the computed value of left is "auto" in Mozilla.Does anyone know how I can do this?

Thank you in advance.

12-20-2002, 11:23 PM
function getAbsPos( oId, tl ) {
var o = (typeof oId = 'String') ? document.getElementById( oId ) : oId;
var val = 0;
while ( o.parentNode.nodeName != "body") {
val += (tl == 'top') ? parseInt( o.style.offsetTop ) : parseInt( o.style.offsetLeft );
o = o.parentNode;
return top;
}Example uses
// Assuming the object's id is 'myDiv'

var top = getAbsPos( 'myDiv', 'top' );
var left = getAbsPos( 'myDiv', 'left' );

// or if you don't know the ID or have an existing object reference

var d = document.createElement( "DIV" );
var div = document.appendChild( d );
var top = getAbsPos( div, 'top' );
var left = getAbsTop( div, 'left' );

12-21-2002, 02:16 PM
That code does not work,top and left are "undefined".I am passing a valid reference to the element (I checked it).
There are some mistakes in the code,like:why does it return top?It should return val.And it should be == instead of =.Fixing these errors make makes left and top "NaN" (not a number).Are you sure that the code is made for Mozilla/Konqueror,in a XHTML page?

12-21-2002, 05:00 PM
Doh, that's what I get for coding quick and not testing it. I'll fix it up and re-post

12-21-2002, 09:07 PM
Okay,thank you.

12-21-2002, 10:50 PM
Here ya go.
function getAbsPos( oId, tl ) {
var o = ( typeof oId == 'String' ) ? document.getElementById( oId ) : oId;
var val = 0;
while ( o.nodeName != "BODY" ) {
val += parseInt( ( tl == 'top' ) ? o.offsetTop : o.offsetLeft );
o = o.parentNode;
return val;

07-03-2008, 07:08 PM
Take a look at this: http://blogs.korzh.com/progtips/2008/05/28/absolute-coordinates-of-dom-element-within-document.html

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum