Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery slideDown with set height and overflow

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.

like image 914
stergosz Avatar asked Jan 27 '12 15:01

stergosz


2 Answers

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

like image 120
Eric Bieller Avatar answered Oct 10 '22 01:10

Eric Bieller


use scrollHeight property, this can make your script dynamic.

$('.button').click(function() {
    $('.text').animate({ 'height': $('.text')[0].scrollHeight }, 1000);
});
like image 43
GusDeCooL Avatar answered Oct 10 '22 03:10

GusDeCooL