Get text width

Discussion in 'Javascript' started by Showtime, Feb 16, 2005.

  1. Showtime

    Showtime Guest

    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, Feb 16, 2005
    #1
    1. Advertising

  2. Showtime

    Showtime Guest

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

    function getElementWidth(Elem) {
    if(document.getElementById) {
    var elem = document.getElementById(Elem);
    } else if (document.all){
    var elem = document.all[Elem];
    }
    xPos = elem.offsetWidth;
    return xPos;
    }

    <span id="test">asdfasdf</span>

    alert(getElementWidth(test)) -> gets the span width


    "Showtime" <> escribió en el mensaje
    news:...
    > 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, Feb 16, 2005
    #2
    1. Advertising

  3. Showtime

    Fred Oz Guest

    Showtime wrote:
    > I answer my own question: it's better to use a span element.
    >
    > function getElementWidth(Elem) {
    > if(document.getElementById) {
    > var elem = document.getElementById(Elem);
    > } else if (document.all){
    > var elem = document.all[Elem];
    > }
    > xPos = elem.offsetWidth;
    > return xPos;
    > }
    >
    > <span id="test">asdfasdf</span>
    >
    > alert(getElementWidth(test)) -> gets the span width


    As a test case, why not:

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


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

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

    --
    Fred
     
    Fred Oz, Feb 17, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. AndrewF
    Replies:
    1
    Views:
    785
    Bruce Barker
    Oct 10, 2005
  2. Xu
    Replies:
    11
    Views:
    8,571
    Andrew Thompson
    Jul 16, 2005
  3. Coder
    Replies:
    1
    Views:
    703
    Cowboy \(Gregory A. Beamer\)
    Jun 24, 2006
  4. John Dalberg
    Replies:
    4
    Views:
    787
  5. RMZ
    Replies:
    2
    Views:
    190
    David Mark
    Aug 2, 2007
Loading...

Share This Page