Hunrik
Hunrik

Reputation: 483

Limiting text with max height

I have a grid layout where I'd like to limit the height of the text, by cutting the text than adding more... link. I used the length to get where i have to cut the text. But when a post contains short lines and divided with enter than they count as a short text but their height is still high. like this:

----------  ----------
|12345678|  |12      |
|9more...|  |34      |
|        |  |56      |
----------  |78      |
            |9more...|
            ----------

So are there any solution to limit the height?

Ps. Sorry for my English.

Upvotes: 0

Views: 220

Answers (2)

Joe Sager
Joe Sager

Reputation: 787

Here is a good solution that will remove a single character from the content until it's height is as specified:

var maxHeight = 70;
var limiter = document.getElementById("limiter");
var height = limiter.clientHeight;
var content = limiter.innerText;
alert("Original Content:\n" + content);
var count = 0;
while (height > maxHeight && count < 100) {
    count++;
    content = content.substring(0, content.length - 1);
    limiter.innerText = content + " more...";
    height = limiter.clientHeight;
}
alert("Adjusted Content:\n" + content);
var html = limiter.innerHTML;
alert("Final HTML:\n" + html);

The count is there just to prevent getting stuck in an infinite loop, just in case. It is not necessary.

Fiddle: http://jsfiddle.net/38p8hhve/

Upvotes: 0

NullPointerException
NullPointerException

Reputation: 446

Make a function which reads every post and if have more than Xpx of height, you will add that 'more...' anchor and also limit the height.

Example:

$('post').each(function(){

    if($(this).height > 50){
         $(this).css('max-height', '50px');
         $(this).append('<a class="more">more....</a>');
    }
});

Then you make another function that listens the class more and if the click its done you quit the max-height property and the more anchor.

Upvotes: 1

Related Questions