Get string length in pixels with JavaScript - javascript

Let's say I have the string "Hello". This string is obviously five characters in length, but what is its length in pixels? Is there an easy way to determine this length in JavaScript? I have thought of a solution where an extra div would have to be displayed to the user, but this way seems hacky and complicated.
In the bigger picture, I am trying to determine how many spaces would be necessary to fill that length of the string. As you can probably tell from above, I think the best option would be to simply measure the length of the string and a single space character from the user's perspective and calculate how many spaces should replace the text based off of that. This is going to be displayed in an HTML input text, by the way.
Thanks.

You can determine the number of pixels the container of the string. You can do this by creating a hidden element in the DOM, setting the inner HTML to the string and then asking for the width.

I don't think their is a good, easy way to do that, except computing the length of a container. The width depends on the font-size, the font, the letter-spacing, it will be different depending on the browser etc...

I've used this to determine the text length in pixels (jQuery syntax):
var txtLen = $(<selector>).text().length * $(<selector>).css('font-size').slice(0,-2);
where selector is whatever you use to target the specific element. Adjust where needed (if the font-size is not set in px).
For example:
var txtLen = $('table td').text().length * $('table td').css('font-size').slice(0,-2);
Real-life use of this was when I needed to determine whether to show the tooltip on a td with a fixed width - if td is wider than its contents, there is no need to show the tooltip.
Things stated in Robin's answer still apply.

Related

Regex / Text Replace in Javascript .. add ellipses at last shown space

I wrote a very simple jquery plugin that clamps lines of an element to a set number of lines. Basically all it does is take the font size, the line height, and an argument passed to the function for max-lines, then it sets a maxheight and css-overflow to hidden.
To be clear, this clamps the actual element with the text, not a containing element.
I am wondering the best way to add an ellipsis to the last shown space. Should I actually truncate the text, then add an ellipsis via regex? If so, whats the best way to truncate characters that aren't shown?
Any help would be appreciated.

Two columns text block with an image

I need some help...
How should I do the markup of a layout with two images and a block of text divided in 2 columns with different width, where the 2nd column starts lower than the first one because of one of those images? Here is a sketch of my layout:
I hope I described my problem explicitly enough.
P.S.: Is it possible actually?
CSS3 has a solution, but it is not standard yet and won't work in older browsers here is a link http://www.css3.info/preview/multi-column-layout/.
Possibly the best idea is to use javascript somehow. Put all the text in the first column and test the height then move portions of the text over to the next column until you have equal columns or until the first column is at a desired height.
Another method is to have predefined proportions eg(2/3 in the first column and 1/3 in the second). Then split the text based on the proportions using character count. This won't be exact and you could use a method similar to the one above to find exact width based on overflow properties, but the characters should average out to be the correct length.
This method is pretty simple and would look like
var txt='Column text...';
var len=txt.length;
var chars=Math.floor(len*.67);
//Assuming you want 2/3 of the text in the first column
document.getElementById('col1').innerHTML=txt.substring(0,chars);
document.getElementById('col2').innerHTML=txt.substring(chars);
//Notice that this could split in the middle of a word so you would need to do
//some checking for the nearest space and the change the break to there.
//Also you could then use the previous method to adjust it if you want something really accurate

What characters will a TextArea wrap at, other than spaces?

I'm working on the latest version of my plugin, Textarea Line Counter (http://mostthingsweb.com/?p=84). To make it even more accurate, I want to identify regions of text that wrap because they are too large to fit on the line (like a sequence of repeated characters).
I'm assuming that browsers only wrap text at spaces. Are there any other characters that lines can be wrapped at? Thank you,
Looks like it depends on the browser, my Opera wraps also on e.g. + % ? $ / ( [ { } \ ° ! ¿
Safari/Chrome on ¿ ? too
(guess there are lots more)
Nice idea for a plugin. Fighting the accuracy issues is going to be a challenge.
There's not a universal catch all for the way textarea is going to handle a string (other than line breaks at spaces), or using word-wrap.
IE produced a break with . , () {} ?, but not with / * = +
In this example, textarea seems to have that "special" feeling like a td
Based on all your advice, I have created a solution. It is rather large, and in fact I think I will make it into a separate plugin, as well as including it in my Textarea Line Counter. It works like this:
Create a div to act as a container, and set the font to something monospaced (i.e. every character is the same width)
Create a span within the container, and place a single letter.
Take the width measurement of the span (which will be the width of the letter, once margins, padding, and some other CSS attributes are cloned)
Create another div within the container and clone its CSS attributes. Set it's width to be two times the width of the letter found in step 3, and record its height.
To test if a character will cause a wrap, set the text of the div to: A[some character]A. [some character] is a character you are trying to test.
Test the height of the div. If it is larger than the height found in step 4, the text has wrapped.
I'm looking forward to releasing this plugin. Thank you again for all your advice.
some browsers will break inside words if the word is longer than the col width,
otherwise they break on spaces.
I notice some browsers set this by default- you can, too in most bowsers with:
textarea{word-wrap: break-word}
you can be sure it is not set by using textarea{word-wrap: normal}

How do I get the total horizontal width in characters of a Label, Button, TextArea, or TextBox?

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
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.
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.
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.

Is it possible to style a heading size according to the length of the heading?

Newspapers often style the heading font for each story according to how much space the words take up. For instance, in this spread, you can see text has been styled to fit one line:
http://www.newsdesigner.com/blog/images/feb05/best/hc6.php
And on this one, you can see different sizes for each headline according to the article size.
http://www.snd.org/snd28/worldsbest/Aripaev_files/Aripaev08.jpg
Is it possible, using some combination of CSS and jquery, to apply styling rules to a heading according to it's length? So for a short heading "A Short Heading" would have a larger font-size and letter-spacing to fit within one line. And "Slightly Longer Heading for an Article Title" would have a smaller font-size and letter-spacing to fit into two lines.
To keep this simple, assume the heading sits above a one-column fixed-width (400px) text block.
I had asked a question like this some time back, but don't recall getting a very good response. Today, though, I have a couple of ideas.
Heading Height vs Single Character Height
For each heading, you could check the height of the heading vs the height of the heading if it had only the first letter (creating a copy of the heading, truncate its text, and check its height off-screen). For instance:
"This is a very long heading" may be 125px tall, where as "T" may only be 42px tall. You could then setup a loop that shrinks the font-size by 1 pixel until the height of the heading is equal to or less than 42px.
Replace Spaces, and Shrink
Another method would be to replace all of the spaces with non-breaking spaces, and then shrink until the width of the header is equal to or less than that of its parent.
As a starting point, suppose you have a class "long" that provides alternative styling for titles longer than the value of the variable "threshold". Then you can set this class on long headings using
$(':header').each(function () {
$(this).toggleClass('long',$(this).text().length > threshold);
})
This is certainly possible to do, but difficult to do well.
A basic alogrithm to do this is to first determine how big your string can be. Next, create your string in a specific size and then see if it is "close enough" to your target. If not, recreate the string in a new size/style and repeat.
Here's a link that will show you how to measure the size of a string in JavaScript:
http://blog.mastykarz.nl/measuring-the-length-of-a-string-in-pixels-using-javascript/

Categories

Resources