JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<div class="parent" id='text'>
Contrary to popular belief Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.
</div>
<br/>
<br/>
<div id='text_2'>
Text that has a different width. You can see it working. need som emore text
</div>
<br/>
<br/>
<div id='text_3'>
Text that has a different width. You can see it working. need som emore text
</div>
<script>
// pre_space is if a space should be before the word we are calculating
// this will be true everythime except for new line words
// str is the string we are testing to see how long it is
// post_space doesn't get used
// append_elem pass the element so that we append to the same element
// to make sure we get the same font size in our tmp_div
function getWidth(pre_space, str, post_space, append_elem){
var pre = (pre_space) ? ' ' : '';
var post = (post_space) ? ' ' : '';
var tmp_div = $('<span style="white-space: nowrap;">'+pre+str+post+'</span>');
append_elem.append(tmp_div);
var width = tmp_div.width();
tmp_div.remove();
return width;
}
// parses the innerText word by word getting the width
// and determining if it is a new line or current line
// and then at the end convert the last line into a link
function linkEndLine(elem_id){
var elem = document.getElementById(elem_id);
var width = $(elem).width();
var text = elem.innerText;
var words = text.split(' ');
var line_width = 0;
var current_line = '';
var lines = [];
words.map(function(word, index){
if(line_width == 0){
line_width += getWidth(false, word, false, $(elem));
}
else {
line_width += getWidth(true, word, false, $(elem));
}
if( (line_width / width) > 1){
lines.push(current_line);
line_width = getWidth(false, word, false, $(elem)); // new line
current_line = '';
}
current_line +=...
CSS
.parent
{
width:250px;
}
#text_2
{
width:100px;
}
#text_3
{
width:500px;
}