How to remove text that is overflown from element in Jquery - javascript

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.

Related

Detect overflow fails in Firefox using (this.clientWidth < this.scrollWidth)

We're trying to detect if an element is overflowing using this simple Javascript code:
this.clientWidth < this.scrollWidth
This works perfectly on Chrome/IE but on Firefox it fails in until there's too much overflowing.
The example can be seen here: http://colnect.com/en/coins/countries#-1;yemen
This page show a list of countries. We do vertical centering of the text if it fits in a single line. If it's too long for one line (which is why we want to detect the overflow), we change it so the text appears in two lines.
In this attachment you can see what happens on Firefox (depending on the width of your window). When the overflow isn't "big enough", it's not detected even though CSS has clearly added the ellipsis for it so it IS overflowing. First 4 "countries" shown are correct (the 4th even broke into two lines) but the others are not.
To recreate, simply start resizing your Firefox window slowly until you see where this breaks.
Any ideas? A different way to detect overflow?
Try this:
if you want to keep full name then, just remove text-overflow:ellipsis; from the selected class or id.
if you want to keep name in one line and no ... in last position, then set white-space: nowrap !important;overflow: hidden; in selected class
In my Firefox browser: (with center align and without text-overflow:ellipsis;)
(with center align and with text-overflow:ellipsis;)
you can choice any one.
I've noticed two things with your website. You are using white-space:nowrap and you have a transition: all on the cell class. I changed those to white-space:normal and disabled the transition and it worked fine with the wrapping.
The reason i disabled the transition is that I found that sometimes it takes a moment to change the text and break it to two lines :)
Give it a try and let me know if that works.
...also keep in mind that having an ellipsis for overflown elements may force the ellipsis to appear because it might be larger in width than the last character. I have encountered some times where without ellipsis the whole text could be shown, while using ellipsis removed my last character.
Please try this CodePen sample.
<div id='mydiv'>Some relatively long line of text to test an interesting question about Firefox behavior.</div>
<br><br><br>
<div id='dbgmsg'></div>
#mydiv {
width: 33%;
border: solid 1px gray;
white-space: nowrap;
overflow: hidden;
}
$(document).ready(function insertAds() {
function printWidthes(){
var clientWidth = $('#mydiv').get(0).clientWidth;
var scrollWidth = $('#mydiv').get(0).scrollWidth;
$('#dbgmsg').html("clientWidth = " + clientWidth + "<br>scrollWidth = " + scrollWidth);
}
$(window).resize(function(){
printWidthes();
});
printWidthes();
});
I've tested it on the latest Firefox version (35.0.1) on Window 7 and its behavior is absolutely correct. When the div size is less than the text size by even only one pixel then clientWidth becomes less than scrollWidth.
Try to test it on your computer; probably you have different Firefox version that causes the problem. BTW, did you saw that the numbers are wrong in debugger / print or it's just your guess? May be your site works wrong because any other reason?
I think this may be related to a (now resolved) bug in firefox.
Perhaps a different way of determining the scrollWidth and clientWidt is the answer (as brilliantly stated in why scrollwidth doesnt work) :
Apparently by hiding the element before reading the scrollWidth gives a different value than when visible.
element=document.getElementById("my_div");
var scrollWidth = $(element).css("overflow", "hidden")[0].scrollWidth;
alert('clientWidt h = ' + element.clientWidth + ', scrollWidth = ' + scrollWidth );
$(element).css("overflow", "visible");

Optimizing text length of limited space

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();
};

Stop text from over running it container

Ive got a container of into which a message gets echoed, the message its self has no fixed size, as its user generated, what can happen though is that if a string of text that is too long is submitted it can over flow its container an break the design..
Is there a way (hopefully with just css, although js is ok) to make the box crop the text and leave it with a ... then i can place a link to the text on another page.
You can obviously stop this happening by using overflow:hidden, but i would like a more elegenat approach rather than just cutting it straight off. I seem to remeber reading about somthing like this with css3, but for the life of me cant figure out what it was called.
Ive made a jsfiddle of the problem here - http://jsfiddle.net/6Fk7B/
CSS property text-overflow:ellipsis, though browser support varies
https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
That should do it for you. All need to be included.
You may also want to include the following browser prefixes:
-ms-text-overflow: ellipsis;
-o-text-overflow: ellipsis;
It won't be perfect in all browsers, but it should be good for most:
http://caniuse.com/#feat=text-overflow
You might want to tryout http://www.mobify.com/blog/multiline-ellipsis-in-pure-css/
The actual code is here http://codepen.io/romanrudenko/pen/ymHFh
Honestly it's tricky to put ellipsis for a paragraph but pretty straight-forward for single line text.
Is this a reasonable starting point for you?
Fiddle: http://jsfiddle.net/QkugN/
Basically you add all the content to the div and hide it using the normal method of overflow:hidden. You also add a tab that, upon hover, displays the rest of the content. If you use absolute positioning for the mouseover state the content will momentarily be removed from the flow and be allowed to overlay any surrounding content. It might not be a complete solution as it stands but it is a pure CSS direction you could explore.
The bit that's doing the business is the General Sibling selector "~" (tilde). Support for it is pretty solid with modern browsers.
Using JavaScript you could achieve this using substring. jQuery isn't necessary, but it makes it a tad easier.
var myText = $('.myBox').text(),
maxLength = 250,
more = '...';
if (myText.length > maxLength) {
myText = myText.substring(0, 250);
$('.myBox p').text(myText + more);
}
See my example example: http://jsfiddle.net/clrux/6Fk7B/14/

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}

Limit displayed length of string on web page

I'm looking for a technique (javascript, CSS, whatever ???) that will let me control the amount of a string that is displayed. The string is the result of a search (and therefore not initially known). A simple Character count approach is trivial, but not acceptable, as it needs to handle proportional fonts. In otherwords if I want to limit to say 70 pixels then the examples below show different character counts (9 and 15) both measuring the same:-
Welcome M...
Hi Iain if I've ...
If you look at Yahoo search results they are able to limit the length of title strings and add ellipsis on the end of long strings to indicate more.
(try site:loot.com wireless+keyboard+and+mouse to see an example of Yahoo achieving this)
Any Ideas?
Perhaps the CSS property overflow: hidden; can help you, in conjuntion with width.
Using a span with fixed width, overflow-x:hidden and white-space:nowrap would be a start.
To get the elipsis in a cross browser scenario will be difficult. IE has text-overflow:elipsis but that is non-standard. This is emulated with -o-text-overflow in Opera. However mozilla doesn't have this. The yahoo Javascript APIs handle this.
Yahoo does this server-side, the truncation and elipsis ('...') is returned in the HTML. Presumably this is done on a character count, and if thats not an option for you then server-side is out.
Other than overflow: hidden I'm not sure CSS can help you here. You could measure the width of the containing element using Javascript, and truncate the text based on that. This could be used in conjunctin with overflow:hidden; so the text elements don't just resize all of a sudden, but you may have to extract the text and add a temporary element onto the page somewhere to do the measurement. Depending on the number of elements to truncate this might not work very well.
Another slightly hacky option is to measure the width of an element containing the letter 'W', then do a character count and truncate if (char_count * width_of_w) > desired_width.
You can use text-wrap: none; to stop text wrapping onto new lines, although this is a CSS3 property and last I checked was only supported by IE (imagine my shock when I found that one out!).
For a cross-browser pure-CSS solution, take a look at Hedger Wang's text-overflow:ellipsis prototype, here:
http://www.hedgerwow.com/360/dhtml/text_overflow/demo2.php
In CSS: .class-name{
width: 5em;
white-space: nowrap;
text-overflow: ellipsis; }
Hope it can help you.

Categories

Resources