One of the issues I hit on beatsearch is that on the Artist page, some artists have long biographies. Really long.
This actually exposes two bugs. The first being the lack of line breaks. The second being, I don’t want to show that much text. This post is about the latter.
There are many different solutions to this rather common problem. Most implementations will stop after a certain number of characters and provide a link for more. I wanted to do something a bit different and instead stop after a certain number of lines. 3 lines to be exact. Oh, and this has to work regardless of whether you are on a mobile device or on a big monitor.
Fun! Especially when it has to work across multiple browsers!
This was actually pretty easy to do. The line-height CSS property was used to figure out the height:
// #biography is the HTML paragraph tag that contains
// the artist's biography
Great! Now I can set the height of the paragraph to 3* the line height
$('#biography').css('height', parseFloat("22.4px") * 3);
And cause text that goes beyond that height to be hidden:
Which gives you this result:
Lastly we have to put in a link in the bottom-right corner so that the user can view the full biography if they wish. This is pretty simple as well thanks to absolute positioning. We can make the biography element relative, which makes it a containing block, and inside the biography element put in an absolute positioned tag. You can read more about containing block and positioning from this helpful w3c article.
// Insert a span tag
var span = $("<span></span>")
The code should be fairly self-explanatory. We position the text 0 pixels from the right and bottom. We need to set the background colour to white so that we don’t show overlapping text to the user. This is probably the one thing I don’t like about this method is setting the background color.
The big benefit over cutting off after x number of characters is that it works regardless of the width of the biography. On a desktop maybe 70 words can fit in 3 lines but on a mobile only 30 words.
Things are a little complicated in Internet Explorer because line-height may not return the height in pixels but rather a unitless number. This is completely valid, just not very helpful. You can get an idea of how to solve it by viewing the fix.
Last thing to do is to set a click handler to that span that removes the span and removes the styles we added to the biography element. But I’ll leave that as an exercise to the user.