Given this:
<p class="summary">Here is some text, could be 5 words, could be 500 words.</p>
I'm grabbing the paragraph height with this code:
var pHeight = $('.summary').height();
And in my case, if it's greater than 32, it's three lines long (which is too long). In that case, I want to trim the text and insert a "Read More..." link. The problem is, how do I figure out where to trim in order to make the text only take up two lines? If only there were some way I could take the char count and multiply it by some number that is the size of each letter. With monospace that would be relatively simple I think, but this is Arial we're talking about.
Any points in the right direction would be appreciated, thanks!
There's no nice way of doing this for a couple reasons. First, different browsers/platforms may render fonts differently (however slight the difference). Second, there's no way from javascript to extract individual character size of a given font (AFAIK).
If I was implementing something like this, I would simply have a constant for longest allowed length and substring
it. I'd also do this server-side as there's no point in sending data to a client that you're not going to use.
Another method (although not one I'd use) would be to put your text in a div with a set width and height, clipping any overflow with overflow: hidden
. Of course, this can potentially leave you with partially cut off words, so I would advise against it.
If your height is too high, you could simply put a 'p' with a white background over the third line and add the "Read More..." in it. And add an height and "overflow:hidden" to your 'p'.
I would use a jquery text expander. There are several out there but here is an example: http://plugins.learningjquery.com/expander/ The slice point is based off of a character count but with some trial and error you should be able to find a character count that gives you two lines.
I've been working with some of this problems for a while and I have cleared some ideas in the meanwhile. It's kind of expensive in code, but it has worked nice for me. There is a similar problem I solve in my blog if you know spanish and need some coding ideas, right now I will just guide you.
You kind of know the size of the container if its meant to have 2 lines, based on the lineHeight of the text. So imagine your container is Ypx high.
As I said, not very cheap, but I've made some tests and the time it takes to get it done is linear, so with few words it will be pretty fast (when you make the check over 10.000 times it takes little less than a sec)
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With