Detect browser wrapped lines via javascript

I have to admit at first I thought this would be a daunting task since there is no way to task browser to tell you where auto wrap line breaks take place.

I’ve created a solution that first wraps each word in a span, then goes through all the spans to determine their top position in container. It then builds an array of indexes of line start and end spans and wraps each line of word spans in a wrapping span.

DEMO: http://jsfiddle.net/KVepp/2/

Possible Limitations:

  • Space added at end of each span may perhaps cause a span to break to
    a new line where text may not.
  • Not sure if each word span needs to be removed once lines are wrapped. ( very simple mod)
  • Assumes no other html in container other than text
  • Needs a little additional work to be turned into a plugin if needed
    for multiple containers
  • regex for words is simple split at space. Likely need additional
    regex for recurring spaces

HTML:

<div id="content">Lorem Ipsum<div> 

CSS:

#content{ position:relative}

JS:

var $cont = $('#content')

var text_arr = $cont.text().split(' ');

for (i = 0; i < text_arr.length; i++) {
    text_arr[i] = '<span>' + text_arr[i] + ' </span>';
}

$cont.html(text_arr.join(''));

$wordSpans = $cont.find('span');

var lineArray = [],
    lineIndex = 0,
    lineStart = true,
    lineEnd = false

$wordSpans.each(function(idx) {
    var pos = $(this).position();
    var top = pos.top;

    if (lineStart) {
        lineArray[lineIndex] = [idx];
        lineStart = false;

    } else {
        var $next = $(this).next();

        if ($next.length) {
            if ($next.position().top > top) {
                lineArray[lineIndex].push(idx);
                lineIndex++;
                lineStart = true
            }
        } else {
            lineArray[lineIndex].push(idx);
        }
    }

});

for (i = 0; i < lineArray.length; i++) {
var start = lineArray[i][0],
    end = lineArray[i][1] + 1;

/* no end value pushed to array if only one word last line*/
if (!end) {
    $wordSpans.eq(start).wrap('<span class="line_wrap">')
} else {
    $wordSpans.slice(start, end).wrapAll('<span class="line_wrap">');
}

}​

Leave a Comment