[thelist] Getting position with Javascript without setting them in Javascript

Andrew Clover and-evolt at doxdesk.com
Sat Sep 24 13:36:01 CDT 2005


Steve James wrote:

> I need to use Javascript to get positions of 
> DIVs on the page, however I am getting nothing back UNLESS I specify 
> the  positions first using Javascript.

True, and that's the only 'standard' way of doing it. However, many 
browsers support the offsetLeft and offsetTop properties on any page 
element, which was originally an IE-only extension.

Unfortunately offset* is rather poorly designed and so to get the 
position relative to the page edge (which is almost always what you 
want) you have to add up the offsetLeft/Top values of all offsetParents 
from the element you're interested in up to the root.

> I have always been under the impression that even if you 
> define a position or dimension in CSS, you can't access it in Javascript 
> via the DOM.

The standard DOM reflects only the information stored in the document - 
you can get the contents of any inline style="..." attribute directly 
from an object's .style property, but you can't find out what other 
style rules from the stylesheet apply to it because that information is 
not part of the document itself.

You *can* read the rules from the stylesheet, but working backwards to 
work out what styles apply to what elements would be an extremely 
tedious exercise in reinventing the browser's own CSS code.

IE gives you a .currentStyle property on elements which you can use to 
find what styles have been applied to it, but it won't work anywhere else.

-- 
And Clover
mailto:and at doxdesk.com
http://www.doxdesk.com/


More information about the thelist mailing list