By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,947 Members | 1,505 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,947 IT Pros & Developers. It's quick & easy.

CSS element dimensions. A problem reading in javascript

P: n/a
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

Dec 9 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On 09/12/2005 13:37, awoodgate wrote:
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

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Dec 9 '05 #2

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

Dec 10 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.