JSFiddle - React, Tailwind, and code Playground
by akmozo
HTML
<p class="comment">Lorem ipsum dolor sit amet ipsum dolor sit amet</p>
CSS
.comment {
width: 180px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
border: 1px solid black;
}
JavaScript
function set_ellipses_by_word(txt_element, max_width){
// if max_width is undefined, we take current text element width
max_width = typeof max_width == 'undefined' ? jQuery(txt_element).width() : max_width;
// get the text element type
var elm_type = jQuery(txt_element)[0].nodeName;
// init vars
var txt = jQuery(txt_element).text(),
// convert our text to an array
arr = txt.split(' '),
str = '', current_width = 0,
// you can adjust this value according to your font and font-size ...
max_margin = 4;
// create a temporary element for the test, it should have the same font properties of the original element
jQuery('body').append('<'+elm_type+' class="txt_temp" style="display:block;float:left;"></'+elm_type+'>');
for(var i=0; i<arr.length; i++){
// we use str to cumulate words every time
// i = 0 : str = "Lorem"
// i = 1 : str = "Lorem ipsum"
// i = 3 : str = "Lorem ipsum dolor sit"
// ...
str += (str != '' ? ' ' : '' ) + arr[i];
// set our temporary text element text
jQuery('.txt_temp').text(str + '...');
// compare our temporary text element width and our max width, It should little than our max width
if(jQuery('.txt_temp').width() < max_width){
current_width = jQuery('.txt_temp').width();
}
}
// remove temporary text element
jQuery('.txt_temp').remove();
if(current_width > 0){
// set ou text element width
jQuery(txt_element).css('width', current_width + max_margin + 'px');
}
}
// original text is :
// Lorem ipsum dolor sit amet ipsum dolor sit amet
// text visible with initial css params with 180px width gives :
// on chrome 38 : Lorem ipsum dolor sit a...
// on firefox 33 : Lorem ipsum dolor sit ame...
// on internet explorer 10 : Lorem ipsum dolor sit a...
// using set_ellipses_by_word gives :
// on chrome 38 : Lorem ipsum dolor sit...
// on firefox 33 : Lorem ipsum dolor sit amet...
// on internet explorer 10 : Lorem ipsum dolor sit...
set_ellipses_by_word(jQuery('.comment'));