Get text width

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

    #1

    Get text width

    Hi! I have a text and I need to get its width in pixels. The font size is
    not fixed. I've been suggested to put the text inside of an invisible div
    and get the div's width. But I would need to force the div to shrink to fit
    the text. Any idea?

    Thanks in advance


  • Showtime

    #2
    Re: Get text width

    I answer my own question: it's better to use a span element.

    function getElementWidth (Elem) {
    if(document.get ElementById) {
    var elem = document.getEle mentById(Elem);
    } else if (document.all){
    var elem = document.all[Elem];
    }
    xPos = elem.offsetWidt h;
    return xPos;
    }

    <span id="test">asdfa sdf</span>

    alert(getElemen tWidth(test)) -> gets the span width


    "Showtime" <diegoman_sin_e sto@usuarios.re tecal.es> escribió en el mensaje
    news:37htagF59a m4iU1@individua l.net...[color=blue]
    > Hi! I have a text and I need to get its width in pixels. The font size is
    > not fixed. I've been suggested to put the text inside of an invisible div
    > and get the div's width. But I would need to force the div to shrink to[/color]
    fit[color=blue]
    > the text. Any idea?
    >
    > Thanks in advance
    >
    >[/color]


    Comment

    • Fred Oz

      #3
      Re: Get text width

      Showtime wrote:[color=blue]
      > I answer my own question: it's better to use a span element.
      >
      > function getElementWidth (Elem) {
      > if(document.get ElementById) {
      > var elem = document.getEle mentById(Elem);
      > } else if (document.all){
      > var elem = document.all[Elem];
      > }
      > xPos = elem.offsetWidt h;
      > return xPos;
      > }
      >
      > <span id="test">asdfa sdf</span>
      >
      > alert(getElemen tWidth(test)) -> gets the span width[/color]

      As a test case, why not:

      <span onclick="alert( this.offsetWidt h);">------</span>


      For more information viewport features & issues, have a look
      here:

      <URL:http://www.quirksmode. org/viewport/compatibility.h tml>

      --
      Fred

      Comment

      Working...