views:

600

answers:

3

I've got a div needs to show the first three items in a list, if that list is bigger than three items, I'd like a button to trigger to expand to reveal all the items. It's possible for me to find out how many items will be in the list via PHP, but this number could be from 0 to 30.

<style type="text/css">
 .box {
  height: 80px;
  overflow: hidden;
 }
 .box li {
  height: 20px;
  background: red;
 }
</style>

<div class="box">
 <ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li> 
  <li>Item 4</li> 
 </ul> 
</div>
<a href="#show-all">Show All</a>

Is there a way I can automatically find the correct height that div needs to expand to? or is there a way I can simply let jQuery expand the div until all of the list elements are visible?

+1  A: 

You could not set the attributes to overflow:hidden to begin with. Record the height on load. Then set the css to overflow until further notice.

/* I believe boxHeight will take the value of .height() in this case */
var boxHeight = $("#myBox").height().css({"height":"100px","overflow":"hidden"});
Jonathan Sampson
A: 

I implemented something very similar a month ago.

If you simply only have three list elements in the list to begin with and add the rest when the 'Show All' button is pressed, it will automatically re-size. You will need to remove the 'overflow: hidden' though.

IllusivePro
+1  A: 

You should be able to read the height of the ul still

alert($(".box ul").height());

should give you the height, no matter what the height of the div is.

So you could do

$(".box").animate({ height: $(".box ul").height()+"px" });
peirix
This worked a treat, thanks :)
Tom