HeyHeyJC
HeyHeyJC

Reputation: 2867

How can I find the line-breaks created by word-wrapping in contentEditable or elsewhere?

I'm trying to find the actual number of lines currently displayed to the user by a browser's layout engine. Finding 'hard' breaks, <'br'> tags etc, is easy enough, but I can't find a way to see, in code, what I can count onscreen.

I have searched here, and there are a few questions/answers implying it can't be done, or is at the least very involved, but they are all several years out of date, and perhaps things have changed.

textContent doesn't do it, and using the div's height doesn't work in this application. Maybe there's a jQuery way I'm unaware of?

Upvotes: 1

Views: 83

Answers (1)

HeyHeyJC
HeyHeyJC

Reputation: 2867

Divide the height of the whole thing by the height of one character. This method works in IE, Safari, FF and Chrome, though the situation is fairly simple, only one size of font etc, so could do with a more thorough workout before being declared The Right Way; it needs empty node checks etc.

function getLineCount(node) {
    if (node) {
        var range = document.createRange();
        range.setStart(node, 0);
        range.setEnd(node, 1);
        var h1 = range.getBoundingClientRect().height;
        range.setEnd(node, node.length);
        return Math.round(range.getBoundingClientRect().height / h1);
    }
};

Is the Tumbleweed Badge also known as crickets?

Upvotes: 1

Related Questions