Finding line-wraps

Viewed 26771

Supposing I have some random block of text in a single line. Like so

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

But for whatever reason (width settings on the containing element, use of text-zoom etc.), on the viewer's screen it displays as two or more lines.

Lorem ipsum dolor sit amet,

consectetur adipiscing elit.

or

Lorem ipsum dolor sit

amet, consectetur

adipiscing elit.

Is there any way to find out via javascript where those line-wraps happen?

$('p').text() and $('p').html() return Lorem ipsum dolor sit amet, consectetur adipiscing elit. regardless of how the text is displayed.

6 Answers

A conceptually simple way that also works when there's internal markup and arbitrary fonts and styles, is to make a first pass that simply puts every word into its own element (maybe 'SPAN', or a custom name like 'w').

Then you can iterate using getBoundingClientRect() to find where the 'top' property changes:

function findBreaks() {
    var words = document.getElementsByTagName('w');
    var lastTop = 0;
    for (var i=0; i<words.length; i++) {
        var newTop = words[i].getBoundingClientRect().top;
        if (newTop == lastTop) continue;
        console.log("new line " + words[i].textContent + " at: " + newTop);
        lastTop = newTop;
    }
}

It sounds slow, but unless the documents are really big you won't notice.

Related