The suggestions from the other answers made me curious, so I put them to the test, and here is what I came up with:
function wrapLines($container) { // get the text from the conatiner var text = $container.text(); // split the text into words var words = text.split(' '); // wrap each word in a span and add it to a tmp var tmp = ''; tmp += '<span>' + words.join('</span><span>') + '</span> '; // remove the text from the container, and replace it with the wrapped words $container.html($(tmp)); // prepare the offset variable and tmp var tmp = ''; var top = null; $container.find('span').each(function(index, word) { $word = $(word); // if this is the first iteration if (top == null) { // set the top top = $word.position().top; // open the first line tmp = '<span class="line">'; } // if this is a new line (top is bigger then the previous word) if (top < $word.position().top) { // close the previous line and start a new one tmp += '</span><span class="line">'; // change the top top = $word.position().top; } // add the content of the word node + a space tmp += $word.text() + ' '; }); // close the last line tmp += '</span>'; // remove the content of the conatiner, and replace it with the wrapped lines $container.html($(tmp)); }
I added a lot of comments, but feel free to ask if something is clear.
To see the code in action (including some fancy colors ;-)) take a look at my script: http://jsfiddle.net/yZnp8/1/
edit :
I put the code from @orb next to my solution here: http://jsfiddle.net/yZnp8/5/ .
A quick comparison with the Chrome Inspector shows that there is a big difference in performance. The @orbs solution takes 754 ms and 17 MB, while my solution takes 136 ms and 14 MB.
Some tips, try limiting your DOM operations (I marked them in the fiddle). They slow down your code because the browser needs to display your page again. I do only 2 , and you are 3 + 2x number of words + 1x number of lines . This probably explains the big difference in speed. And the longer the text, the greater the difference.
Don't try to break @orb's solution, just trying to help and explain the differences ...
Pevara
source share