CSS element dimensions. A problem reading in javascript

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • awoodgate

    CSS element dimensions. A problem reading in javascript

    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

  • Michael Winter

    #2
    Re: CSS element dimensions. A problem reading in javascript

    On 09/12/2005 13:37, awoodgate wrote:
    [color=blue]
    > 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?[/color]

    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
    getComputedStyl e method in certain browsers.

    var o, dV, cS;

    /* Test for method support */
    if(document.get ElementById && (dV = document.defaul tView)
    && dV.getComputedS tyle)
    {
    /* Obtain reference to element and computed style object */
    if((o = document.getEle mentById('myEle ment'))
    && (cS = dV.getComputedS tyle(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 getComputedStyl e, 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.get ElementById) {
    if((o = document.getEle mentById('myEle ment'))
    && (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.

    Comment

    • awoodgate

      #3
      Re: CSS element dimensions. A problem reading in javascript

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

      Comment

      Working...