I\'ve looked around at similar SO posts related to this, but none deal with exactly what I am looking for. Say I have some text, I throw it in a div, and add some arbitrary
The suggestions from the other answers made me curious so i put them to the test, and this 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 += '' + words.join('') + ' ';
// 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 = '';
}
// 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 += '';
// change the top
top = $word.position().top;
}
// add the content of the word node + a space
tmp += $word.text() + ' ';
});
// close the last line
tmp += '';
// remove the content of the conatiner, and replace it with the wrapped lines
$container.html($(tmp));
}
I added plenty of comments, but feel free to ask if something isn't clear.
To see the code in action (including some fancy colors ;-) ), have a look at my fiddle: 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 Chrome Inspector shows that there is a big performance diiference. @orbs solution takes 754ms and 17MB while my solution takes 136ms and 14MB.
A little word of advice, try to limit your DOM operations (I marked them in the fiddle). They slow your code down, as the browser needs to render your page all over again. I do only 2, while you do 3 + 2x number of words + 1x number of lines. This is probably what explains the big difference in speed. And the longer the text, the bigger the difference will become.
Not trying to break @orb solution down, just trying to be helpful and explain the differences...