Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Get text width

Reply
Thread Tools

Get text width

 
 
Showtime
Guest
Posts: n/a
 
      02-16-2005
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


 
Reply With Quote
 
 
 
 
Showtime
Guest
Posts: n/a
 
      02-16-2005
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" <(E-Mail Removed)> escribió en el mensaje
news:(E-Mail Removed)...
> 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
>
>



 
Reply With Quote
 
 
 
 
Fred Oz
Guest
Posts: n/a
 
      02-17-2005
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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Using % on a table width, is it possible to get the width in pixel size? RMZ Javascript 2 08-01-2007 11:01 PM
Can't get table cell width with text field to get smaller John Dalberg HTML 4 10-18-2006 03:00 PM
Drop Down List Border Width vs Text Box Border Width Coder ASP .Net 1 06-24-2006 01:27 PM
Textbox width scaling to width of data not width of page? AndrewF ASP .Net 1 10-10-2005 04:38 PM
JComboBox width, dropdown list width Xu Java 11 07-15-2005 11:54 PM



Advertisments