I'm looking for a way to wrap a around text lines and I found a solution at "Wrap each line of paragraph in a span" that clones a text, split, wrapped each line in <span>
and then output the data in a new element.
But a problem occurs in the output. The outputed <spans>
are inside a div with a set width in the CSS, width:500px
. Odd-lines spans recognize the width and if a word overflows the width, it starts a new line.
Those new lines, for whatever reason, stop halfway and start a new line. That new line then uses the full width and creates a new line if there's an overflow. That new line, also stops halfway and creates a new line.
The process repeats itself until there's no more lines to create.
How do I force created <spans>
to use the entire width of a created line? I.E. force to continue to put words into a span until there's an overflow? The problem occurs on even-lines.
Here's my JS code:
function trimByPixel(str, width) {
var spn = $('<span style="visibility:hidden"></span>').text(str).appendTo('body');
var txt = str;
while (spn.width() > width || txt.charAt(txt.length-1)!="") { txt = txt.slice(0, -1); spn.text(txt + "..."); }
return txt;
}
var stri = $(".str").text();
function run(){
var s = trimByPixel(stri, $(".str").width()).trim()
stri = stri.replace(s,"")
$(".result").append("<span>"+s+"</span>");
if(stri.trim().length > 0){
run();
}
}
run();
Here's a working example. The even-lined <spans>
are the ones with a black background.
function trimByPixel(str, width) {
var spn = $('<span style="visibility:hidden"></span>').text(str).appendTo('body');
var txt = str;
while (spn.width() > width || txt.charAt(txt.length-1)!="") { txt = txt.slice(0, -1); spn.text(txt + "..."); }
return txt;
}
var stri = $(".str").text();
function run(){
var s = trimByPixel(stri, $(".str").width()).trim()
stri = stri.replace(s,"")
$(".result").append("<span>"+s+"</span>");
if(stri.trim().length > 0){
run();
}
}
run();
$('.str').remove().delay(10);
.message-contain {white-space: normal;width:500px}
.message-contain .str{
width:500px;white-space:normal;
}
.message-contain .result span{
display:block;
}
.message-contain span:nth-child(even) {
color: #fff;
background: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="message-contain"><div class="str">
I’m up to something. Learning is cool, but knowing is better, and I know the key to success. Bless up. They never said winning was easy. Some people can’t handle success, I can. I told you all this before, when you have a swimming pool, do not use chlorine, use salt water, the healing, salt water is the healing. Put it this way, it took me twenty five years to get these plants, twenty five years of blood sweat and tears, and I’m never giving up, I’m just getting started.
</div><div class="result"></div></div>