Optimizing text length of limited space - javascript

I am displaying text strings of varying characters and length in a div of fixed width. I'd like to fit as much text as possible in the allotted space. My current approach is to limit the number of text characters in the following way
var n = //some number
string = string.substr(0,n);
The problem with this approach is that different characters have different widths so while it can cap over spill it often leaves unused space. I've tried giving the containing div the following css properties.
div{
width:200px
white-space:nowrap
}
But the text still wraps to the next line down once it over spills the width. Can someone help me out with a good practice way of addressing this problem.

You might try text-overflow
From quirks mode:
text-overflow comes into play only when:
the box has overflow other than visible (with overflow: visible the text simply flows out of the box)
the box has white-space: nowrap or a similar method of constraining the way the text is laid out. (Without this, the text would wrap to the next line)
Style change:
div{
width:200px;
white-space:nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Working demo

Calculate the actual width of the text using a method such as the one described here: https://coderwall.com/p/kdi8ua.
Then keep adding characters until the width is larger than the width of your element, and remove 1.
Here is the function from the site linked to:
// Calculate width of text from DOM element or string. By Phil Freo <http://philfreo.com>
$.fn.textWidth = function(text, font) {
if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
$.fn.textWidth.fakeEl.html(text || this.val() || this.text()).css('font', font || this.css('font'));
return $.fn.textWidth.fakeEl.width();
};

Related

How to remove text that is overflown from element in Jquery

So I am working on a web app, and this is my layout. The divs use
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
This visually is fine, and is also fine in a JSFiddle. But with the ability to make very long names has issues in the web app. This issue comes from the fact that it isn't technically removing the overflown text. It (as you would think with the word "hidden") hides it. How would you go about detecting overflown text in the ".Name" element and removing it? I would like to keep the same look and rules. Just the text that is hidden is removed.
LINK - https://jsfiddle.net/t29ffzan/12/
The issue is that not all letters take up the same amount of space as each other. For instance I and M where M (guessing) is ~ 3x as big as I. See this explanation.
However, you can guess and get close but there's still no guarantee.
$('.Name').each(function() {
let text = $(this).text();
let width = $(this).parent('.Box').outerWidth();
let fontSize = 18 - ( 18 * 0.35 ); // Hardcoded from CSS
let count = width/fontSize;
text = text.substr(0, count);
$(this).text(text);
});
This fiddle is a working example of the above and uses the font-size in the CSS and removes ~ 35% to allow for more characters but depending on the actual letters uses the results may vary widely.
You could use a fixed width font as all the characters should take up the same amount of space. However, results still aren't going to be perfect.
Your best bet is the limit the character count when the name is created instead of having to go back and try and parse it after the fact.
For anyone that comes to this post, max-width: 40ch; worked best for me.

Javascript split text string to fit within div element pages

I have been using overflow scroll to display the text. I realize that the overflow property can detect when the data is larger than will fit.
I need to fill one div element, then another, and so on until all the data is set within pages. The breaks can't break a word.
Only one page/div will be display: block; and the rest will be display: none;
What is the best way to allow data to be displayed on multiple div pages?
Why not you use css for this purpose?
<div style="height:50px; width:50px; overflow:hidden">testing</div>
Ali is right in using CSS to address this, but you should use the CSS word-wrap property to easily acheive your desired effect with the overflow content, as Ali's example edited below.
<div style="height:auto; min-height:50px; width:50px; word-wrap:break-word;">testing<div>
The word-wrap property is now supported in all major browsers.
Also as shown above, if you want to be sure that all the text shows as well as wraps in the correct place, then change your height CSS to 'height:auto; min-height:50px;'. This will allow the div to expand in height to show any overflow that would normally be hidden just defining a fixed height, while retaining the preferred size of 50px if possible, and retaining the desired word wrap not breaking a word in the middle.
The only exception where this will not work, is if a word is so long as to be longer than the width of the containing div, in which case it will break the long word at the last character that will fit on the line before continuing the word on the next line.
It's got to be an awfully long word though to run into this. If you use auto for the width property as done in the example with the height, it will fix the word break problem by allowing the width of the div to change, although in page layout it is usually more important to constrain a width much more than a height.

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

How do I find space between lines in HTML?

This is a follow-up question to a previous question of mine. I am trying to find a way to find the exact location of each line of text in an element.
I was able to find the css lineHeight attribute (see previous answer). The problem is that the height of my element is slightly larger than the cumulative height of the number of lines times the lineHeight.
An example:
I have a <p> that is 2010px tall without padding, border, or margin, (scrollHeight, offsetHeight, and clientHeight all report the same,) and has 89 lines in the browser. The lineHeight of the computedStyle() is 22.
2010 / 22 = 91.37 lines
With small elements I can just floor the value to get the correct number of lines, but run into the above problem with larger elements where I cannot accurately get the exact number of lines.
My assumption is that there is some small space between these lines of text I am not taking into account. Any idea how to find it? Does it have to do with font types? Is it automatically set by the browser? Any documentation would be especially helpful.
Thanks!!
Update:
So I have 26 superscripts in my <p>, each of which protrude up 2px, extending the lineHeight of those lines on which they appear to 24px, which accounts for my missing space. (Woot! Thanks so far!)
I guess the boat I am in now is that I need to find a way to dynamically calculate how much they protrude above the normal top of the line, or discover how much higher the baseline of a <sup> is above the normal baseline. (Vice-versa for a <sub>.)
Otherwise, could I determine that with CSS?
Providing my own answer, as #lanzz's is incomplete to some extent.
If you define the block element as:
div {
font-size: 10px;
line-height: 10px;
height:30px;
margin-top: 0px;
margin-bottom: 0px;
border: 0px;
overflow-y: hidden;
padding: 0px;
}
you will get sufficient space for EXACTLY 3 lines. However, if you have sub-scripts or super-scripts less lines are visible. By removing the overflow you can force it to only display 3 lines of space.
This is demonstrable at: http://jsbin.com/ogoruy/4/
Superscript and Subscript are 'inline-block elements':
The height of the inline box encloses all glyphs and their half-leading on each side and is thus exactly 'line-height'.
When there is only one value of 'line-height' for all inline boxes in a block container box and they are all in the same font (and there are no replaced elements, inline-block elements, etc.), the above will ensure that baselines of successive lines are exactly 'line-height' apart.
http://www.w3.org/TR/CSS2/visudet.html#line-height
Superscripts and subscripts usually protrude above and below the line boundaries, as illustrated in this demo — you see that the left example has more apparent space between the lines than the right one, even though they have the same line-height. Unfortunately, browser "typography" (if you can call it that) does not allow you to determine how much the sub/super-scripts protrude, so you cannot take that into account when you calculate the actual line heights.

Place ... in the text that appears in a div with overflow hidden in javascript

I have a div with this CSS class:
.textodiv{ height:29px;overflow:hidden;}
The size of the text that appears is very variable. With the CSS above, it appears about 2 lines and hides the rest. So there you have it as I wanted.
The problem is that I want to put three dots at the end of the text being displayed to give the idea of continuity. But how how far the text is displayed?
I tried to limit the number of characters, but not as the font of fixed size and the line break changes according to the size of the words, this solution does not effective.
Any suggestions?
For a single line approach you can do this through CSS, add the following to your css rule:
text-overflow: ellipsis;
white-space: nowrap;
If you want multiple lines you will have to use a JavaScript approach, which can be found at:
Cross browsers mult-lines text overflow with ellipsis appended within a width&height fixed div?

Categories

Resources