How to check row count using jQuery

Example: a div with a width of 30 pixels with the words "this is text". Let's say that since the width is narrow, it is displayed on the page as follows:

this is
is an
text

(3 lines). Is there a way in jQuery to tell how many lines are required to render per page? For example, something like $("#container").lineCount() .

Business goal: if my content exceeds a certain number of lines, I want to manipulate it so that the scrollbar does not appear, but I also have a fixed height, so I do not want to mess with css prop overflow.

Thanks!

+7
source share
1 answer

This is difficult, but can be done even if there is no given line height or other style. This is due to a bunch of moving parts.

First create a "sacrificial" container <div> . Fill it with the known number of lines of text, one character at a time and place it far beyond the 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 row height in pixels displayed by this browser. Let's pay attention to the field that needs 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 field, if allowed to reach its natural sizes displayed by the browser:

 var numLines = $measureDiv.height() / lineHeight; 

We need clone() , because the source field that needs to be measured can have its height limited by the current styles and page layout.

Now a little cleanup:

 $calcdiv.remove(); $measureDiv.remove(); 

Here is an example: http://jsfiddle.net/redler/FuWue/

+9
source

All Articles