[thelist] div's pixel coordonates

Andrew Clover and at doxdesk.com
Mon Apr 22 12:42:01 CDT 2002


Catalin Salagean <cds at orizont.net> wrote:

> Is there a way (mainly Javascript) to find out the exact
> pixel coordonates of a given <div> ?

The standard DOM say no. You can read what the 'top' and 'left'
styles were set to using -

  x= parseInt(document.getElementById('mything').style.left);
  y= parseInt(document.getElementById('mything').style.top);

but that only works if the element has them defined in pixels in
an inline style attribute, eg.

  <div id="mything" style="left: 100px; top: 100px;">

otherwise you'll get nothing, or the position defined in a
different unit. The exception is Opera, where you can read
style.left/top and always get an integer position! This is
useful but wrong and will probably be fixed in Opera 7.

Both Mozilla/N6 and IE5 (and I think also Konqueror) support
this extension for all elements:

  x= document.getElementById('mything').offsetLeft;
  y= document.getElementById('mything').offsetTop;

This gives you the integer position of an element's padding edge
relative to the "offsetParent". If you need to find the element's
border edge you'll have to add the value of 'clientLeft'. If you
need to find the element's margin edge or content edge you are
stuck, without a lot of faffing around. There is also
offsetWidth/Height to tell you how big the element is.

The 'offsetParent' is always the document in Mozilla. In IE,
it's the nearest <td> ancestor of the current element, or the
document if there is no <td> ancestor - in IE6. In IE5, any
positioned element can also be an offsetParent. Basically you
have to loop through offsetParents adding the offsetLeft and
the clientLeft of each ancestor, and the total is the page
co-ordinate of your element. This is extremely annoying, but
if you know your element is directly inside <body> you can
ignore the issue.

IE4 behaves the same but you have to access the element through
document.all instead of documnet.getElementById. N4 can read
the positions of absolute-positioned elements only, using:

  x= document.layers['mything'].left;
  y= document.layers['mything'].top;

Again if you have nested layers you will have to add up all
the ancestors' values. Any relative-positioned layers will have
relative co-ordinates so that is not much use to you.

I'd put all this together to come up with a reliable readPosition
function for IE, N4, Moz, Opera and Konq. If I could be bothered.
;-)

--
Andrew Clover
mailto:and at doxdesk.com
http://and.doxdesk.com/



More information about the thelist mailing list