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

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.

Related

How to get nth line of a text by JavaScript?

Consider a simple html element as
<div id="test">
a long text without line break
</div>
The browser will create lines based on the glyph and font sizes. After text arrangement by the browser (e.g. depending on the window width), how to get the lines of the text by JavaScript?
For example:
How to get the total number of lines
How to get the first line as appeared in the current window?
How to get the nth line?
No, there is no API that gives you access to the rendered text after layout has occurred. The only way to approximate this is pretty hacky, i.e. add words into a container one at a time and see when it changes height. See this related question:
detecting line-breaks with jQuery?
Yeah, who'd have thought it, even jQuery doesn't do this! ;-)
2 easy solutions and a extremely hard one.
1 Formatting the text.
Inside a pre & textContent
html
<pre>hello
hello1
hello2</pre>
js
document.getElementsByTagName('pre')[0].textContent.split('\n')
http://jsfiddle.net/gq9t3/1/
2 Adding br's
Inside a div with br & textContent
html
<div>hello<br>hello1<br>hello2<br>pizza</div>
js
document.getElementsByTagName('div')[0].innerHTML.split('<br>')
http://jsfiddle.net/gq9t3/4/
To much trouble
css
div{width:100px;line-height:20px;}
html
<div>hello dfgfhdhdgh fgdh fdghf gfdh fdgh hello1gfhd gh gh dfghd dfgh dhgf gf g dgh hello2</div>
js
document.getElementsByTagName('div')[0].offsetHeight/20
easy way to find the number of lines but you need to calculate the text width to find the corresponding line content.
http://jsfiddle.net/gq9t3/3/
I was attempting to style the first line of text, but text-transform:uppercase messed it up. http://zencode.in/lining.js/ helped with addressing the first line (responsively!), so perhaps this library will assist with your issue too.

Truncating text inside a div [duplicate]

This question already has answers here:
Truncating long strings with CSS: feasible yet?
(6 answers)
Closed 9 years ago.
I have some dynamic text (comes from a database) and I need to fit into a div
My div has a fixed size. However, when the text becomes too long, it breaks into two lines. I would like to put three dots at the end of longer texts to make them fit inside a single line.
For example: My really long text becomes My really lo...
I have committed several attempts, but basically all of them depend on counting characters. That is, whatsoever, not really fortunate, for characters do not have a fixed width. For example, a capital W is much wider than an small i
Therefore, I encounter two main problems with the character-counting approach:
If the text has many narrow characters, it gets cut and appended with ..., even if the text would actually fit on one line afore trimmed.
When the text contains many wide characters, it ends up on two lines even after I cut it to the maximum number of characters and append the dots.
Is there any solution here (JavaScript or CSS) that takes the actual width of the text into consideration, and not the number of characters?
Use these styles:
white-space: nowrap; /*keep text on one line */
overflow: hidden; /*prevent text from being shown outside the border */
text-overflow: ellipsis; /*cut off text with an ellipsis*/
Apart from ellipsis, I would suggest display the whole text on mouse hover using tooltip.
fiddle
I would suggest Trunk8
You can then make any text fit to the size of the div, it trims the text that would cause it to go beyond 1 line (options are available to set amount of lines allowed)
E.g
$('.truncate').trunk8();
You should look at css ellipsis : http://www.w3schools.com/cssref/css3_pr_text-overflow.asp

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}

Get string length in pixels with 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.

Categories

Resources