Tom
Tom

Reputation: 34366

Reveal Hidden Elements in jQuery

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?

Upvotes: 2

Views: 874

Answers (3)

peirix
peirix

Reputation: 37771

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" });

Upvotes: 1

IllusivePro
IllusivePro

Reputation: 19

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.

Upvotes: 0

Sampson
Sampson

Reputation: 268414

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"});

Upvotes: 1

Related Questions