0

I'm having a problem with a coding example I found at Wrap each line of paragraph in a span. Basically it clones text in a div and outputs the text wrapped in a span in another div.

The problem I'm having is that during the cloning process, words get cut off because the length of the word goes over the width that's set in CSS.

Example:

<span>I’m up to something. Learning is cool, bu</span>
<span>t knowing is better, and I know the key t</span>

Is there anyway to get words to not overflow? I've try setting overflow:auto in css and it won't recognize it.

function trimByPixel(str, width) {
  var spn = $('<span style="visibility:hidden"></span>').text(str).appendTo('body');
  var txt = str;
  while (spn.width() > width) { 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);
.str{
  width:300px;
  }
  
  .result span{
  display:block
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
Gregory Schultz
  • 864
  • 7
  • 24

1 Answers1

1

The problem is the trimByPixel() function which just checks if a string is small enough to fit a given width but doesn't care if it's right in the middle of a word.

To know if we're going to cut-off a word, we can check what character the last character inside the string actually is. So for simplicity we can check if it's an empty space and in case it is, cutting off is fine. A more sophisticated test could check if it's a character from a-z A-Z 0-9.

while (spn.width() > width || txt.charAt(txt.length-1)!=" ")
obscure
  • 11,916
  • 2
  • 17
  • 36
  • Thanks. This has been a big problem for me and I finally solved that part. A new problem was come up but that's another question. – Gregory Schultz Feb 20 '20 at 21:04