jQuery slideDown with set height and overflow

stergosz picture stergosz · Jan 27, 2012 · Viewed 21.3k times · Source

I have the following HTML code

<div class="text">bla bla bla bla</div>
<div class="button">Show</div>

And the CSS

.text{
  height:100px;
  overflow:hidden;
}

Assume .text div has way more text and what I do is hide the amount of text below 100px.

How can I slideDown() the div so I can view the text when I click the button?

Using $(".button").slideDown(); doesn't work because I need to remove the height and then slideDown() but this will not work either.

Answer

Eric Bieller picture Eric Bieller · Oct 5, 2012

I like Shankar's solution but the functionality breaks down after the first two clicks.. This is because the auto class gets overwritten by the inline height style. So instead I altered the height attribute only.

Here's my go at it:

$(".button").click(function(){
    $box = $(".text");
    minimumHeight = 100;

    // get current height
    currentHeight = $box.height();

    // get height with auto applied
    autoHeight = $box.css('height', 'auto').height();

    // reset height and revert to original if current and auto are equal
    $box.css('height', currentHeight).animate({
        height: (currentHeight == autoHeight ? minimumHeight : autoHeight)
    })
});

One flaw is that if you add padding to the box you get some ugly jumping. Open to any solutions to fix that.

Here's a demo

Improvements and suggestions are very welcome