views:

159

answers:

3

The Label, Button, TextArea, and TextBox (abbreviated LBTT from now on) are capable of displaying strings of text. Is there any way to look at a already sized LBTT object, and determine the number of characters that might fit per line of the given object.

For instance, let us say that I have a textArea that is fixed in its width. Is there any way of asking this textArea object how many characters it can hold horizontally? Conceptually, something like a .getHorizontalCharacterWidth() method?

Here is my "visual" ascii Label example. The "-" and "|" are supposed to represent the vertical and horizontal edges of the Label, respectively.

 -------
|       |
|ABCDEFG|
|       |
 -------

As you can see, this label can hold up to 7 characters per horizontal line (In this case A-G)? So if you called my imaginary .getHorizontalCharacterWidth() on this Label it would return 7. Question is, how would you go about implementing .getHorizontalCharacterWidth()?

Assume that I am using a fixed width font.

Thank you

A: 

In two cases, this already exists in plain html attribute form.

Text area:

<textarea name="" cols="10" rows=""></textarea>

Text input:

<input name="" type="text" size="10" />

The more general cases, labels and buttons, are more difficult. An 'i' character, for example, is much narrower than an 'm', for example. If you constrain usage to a monospaced font it gets a lot easier, but that's probably not what you're looking for.

graphicdivine
A: 

I assume you want to wrap text in some smart way in a text area or similar control.

I have asked a similar question a while ago, and basically the width can not be determined.

Your only solution is to either use the available HTML attributes or to assume each character has the same average width and calculate with some buffer zone.

Drejc
A: 

Yes, assuming as you say the text area uses a monospaced font, the aTextArea.getCharacterWidth() should give the number of characters available horizontally. Though it will only return the html property cols which returns the browser default width (or whatever you set it to using aTextArea.setCharacterWidth()) ignoring the CSS specified width.

Though if you know the font size in pixels you can get a rough estimate of how many characters is visible by dividing the pixel width with the pixel font-size. Beware that this may vary depending on the font's character height/with ratio, and that some browsers will return the width either including or excluding the scrollbar if present.

Stein G. Strindhaug