Reputation: 19443
Example: a div with width of 30px with the words "this is text". Let's say that, since the width is narrow, it renders on the page like this:
this
is
text
(3 lines). Is there a way in jQuery to tell how many lines it takes to render to the page? For example, something like, $("#container").lineCount()
.
Business purpose: if my content exceeds a certain number of lines, I want to manipulate it so that a scroll bar does not appear, but I also have a fixed height, so I don't want to mess with overflow css prop.
Thanks!
Upvotes: 7
Views: 4495
Reputation: 23943
This is tricky but can be done, even if there is no specified line-height or other style. It does involve a bunch of moving parts.
First, build a "sacrificial" container <div>
. Fill it with a known number of lines of text, one character each, and position it far off-screen:
// calculate height per line
$calcdiv = $('<div/>').css({
width: '50px',
position: 'absolute', // don't affect layout
left: '-2000px' // position far off=screen
}).html('A<br />B<br />C<br />D<br />E'); // add five lines
$('body').append( $calcdiv ); // make the browser render it
var lineHeight = $calcdiv.height()/5; // average height per line
Now we know the approximate height of a line, in pixels, as rendered by this browser. We turn our attention to the box to be measured:
$origDiv = $('div#div_to_measure');
$measureDiv = $origDiv.clone(); // clone it
$measureDiv.css({
position: 'absolute',
left: '-1000px', // position far off-screen
height: 'auto' // let it grow to its natural full height
});
$('body').append( $measurediv ); // add it to the DOM, browser will render it
...and now we know the approximate number of lines in the box if allowed to attain its natural dimensions as rendered by the browser:
var numLines = $measureDiv.height() / lineHeight;
We have to clone()
because the original box to be measured may have its height restricted by the current page styles and layout.
Now some cleanup:
$calcdiv.remove();
$measureDiv.remove();
Here's an example: http://jsfiddle.net/redler/FuWue/
Upvotes: 9