Finding line-wraps

Well, if you want something that’s ridiculously simple and probably too useless for you (it’ll need major modification if you have any sort of HTML inside the paragraph), then have a look at this:

var para = $('p');

para.each(function(){
    var current = $(this);
    var text = current.text();
    var words = text.split(' ');

    current.text(words[0]);
    var height = current.height();

    for(var i = 1; i < words.length; i++){
        current.text(current.text() + ' ' + words[i]);

        if(current.height() > height){
            height = current.height();
            // (i-1) is the index of the word before the text wraps
            console.log(words[i-1]);
        }
    }
});

It’s so ridiculously simple it might just work. What this does is to break up the text by spaces, then append the words back word by word, watching for any increase in the height of the element, which would indicate a line wrap.

Have a look at it here: http://www.jsfiddle.net/xRPYN/2/

Leave a Comment