I'm trying to make a string fits in a determined area (td
) without breaking line. The problem is: It needs to ...
- Fit while resizing
- Fit in
N
kinds of resolution - Add
...
at the end when needed (and don't when not needed) - Accept the change of
font-size
,font-weight
, andfont-family
Based on the answers on Novon's question, I made the following code:
CSS (// Just adding some styles to break the line)
.truncated { display:inline-block; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
jQuery (// Find all td that contains a .truncated
element. Getting the real width (by removing the content and adding it again) of the td
. Applying, if needed, minWidth on the td
)
jQuery('.truncated').closest('td').each(function() {
var text = jQuery(this).text();
var widthOriginal = jQuery(this).width();
var widthEmpty = jQuery(this).text('').width();
jQuery(this).text(text);
if(widthOriginal >= widthEmpty){
var width = (parseInt(widthEmpty) - 10) + 'px';
jQuery(this).css('maxWidth', width);
jQuery(this).text(text + '...');
}
});
the result (as expected from the above code) is:
but it should be:
I was thinking, maybe try to find the first line
of the string and remove the rest but didn't find a way to do that (and it's a lot of "workaround" for my taste). Is there a better way to do that?