views:

326

answers:

3

I have a div with text loaded from a database in it. I have no control over the length of the text and want to calculate or count the number of lines it wraps to so I can hide all except a small segment at the beginning until a user clicks on "more". Is there any way to do this with javascript?

Thanks in advance.

A: 

In my advice you have 2 way of do this using Progressive enhancement:

1) Write all the text in it and then use javascript to collapse it (splitting for line-break) (placing for example a "..." link to show up all the div)

2) Generate server-side an href link "..." that when clicked make you explode the text, on page/content load replace the "a" link and make it use an ajax call instead.

I will use the 2nd option.

kentaromiura
+1  A: 

You should be able to do this be retrieving the height of the div and dividing it by the font's line height, assuming the div's height is controlled by the amount of content within it.

document.getElementById('my_div').offsetHeight;

and

document.getElementById('my_div').style.lineHeight;
NathanGaskin
Only if there's no pictures, styles or other stuff in there that changes the line height.
Marcus Downing
Yes its got heading styles in it as well, I could factor that in but I want the cleanest solution possible.
Jesse Gibbs
+1  A: 

Use an element with overflow: hidden, and change that style when they click on more.

HTML:

<div>
  <div id='content'>...</div>
  <div><a id='morebutton'>More</a></div>
</div>

CSS:

#content {
  height: 200px;
  overflow: hidden;
}

JS (using jQuery):

$("#morebutton").click(function() {
  $("#content").css(overflow: "visible");
}
Marcus Downing