CSS element dimensions. A problem reading in javascript

A

awoodgate

Hi, I'm trying to read the width of a css absolutely positioned element

in javascript. If I use an id selector or a class definition then the
width is null, but if I use an inline style then it works. Can anyone
tell me why?

Andrew
 
M

Michael Winter

Hi, I'm trying to read the width of a css absolutely positioned
element in javascript. If I use an id selector or a class definition
then the width is null, but if I use an inline style then it works.
Can anyone tell me why?

Spartanicus told you /why/ in ciwas: the style object represents the
inline style declarations applied to an element.

To access the computed CSS values of an element, you can use the
getComputedStyle method in certain browsers.

var o, dV, cS;

/* Test for method support */
if(document.getElementById && (dV = document.defaultView)
&& dV.getComputedStyle)
{
/* Obtain reference to element and computed style object */
if((o = document.getElementById('myElement'))
&& (cS = dV.getComputedStyle(o, null)))
{
/* cS now references the computed style object, and
* can be used like the style property of an element.
*/
alert(cS.width); /* '??px' */
}
}

However, IE doesn't support this. Though it does have its own
alternative, the currentStyle property, it is far inferior
(feature-wise) and may not be of much use. For instance, if an explicit
width property is not defined, rather than returning the actual width as
with getComputedStyle, it return 'auto'. Even if a width declaration
does exist, the property value is returned verbatim, meaning that it's
up to you to perform any conversion to pixels (if necessary) yourself.

var o, cS;

if(document.getElementById) {
if((o = document.getElementById('myElement'))
&& (cS = o.currentStyle))
{
/* ... */
}
}

You are more likely to benefit from using other properties, like
offsetWidth, to determine the dimensions.

Mike
 
A

awoodgate

Michael, thanks for your knowledge and time. offsetWidth is, as you
suggest, a much better idea.
Andrew
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top