Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add animation when change CSS height property

I hope you all are having a great day

I'd like to add animation to that piece of code. I tried using animate() . But it didn't work, maybe it's because of the lack of my knowledge in javascript.

Please tell me if it's possible with this code, or do I need to try something else? what do you suggest?

Thank you very much in advance.

Here is the HTML code:

<div id="description_wrapper">
    Text content.<br/>
    See; More Text content.
</div>

<button class="learn_more" id="lm_more" href="#">Learn more</button>

The CSS

#description_wrapper
{
    margin: 0 auto;
    margin-top: 25px;
    height: 0;
    overflow: hidden;
}

The jQuery

$('#lm_more').click(function(event){
    event.preventDefault();
    if($('#description_wrapper').css('height') > '1px') {
        $('#description_wrapper').css({'height': '0px'});
        $('#lm_more').html('Learn More');
    }
    else
    {
        $('#description_wrapper').css({'height': 'auto'});
        $('#lm_more').html('Learn less');
    }
});

View the code here http://jsfiddle.net/Gbspx/11/

like image 536
Bilal Khoukhi Avatar asked Jun 14 '13 19:06

Bilal Khoukhi


2 Answers

You can use some CSS3 Transitions to do this very easily and smoothly. Switch your current CSS with this:

#description_wrapper
{
margin-top: 25px;
height: 0;
overflow: hidden;
-webkit-transition: all .8s ease;
-moz-transition: all .8s ease;
-ms-transition: all .8s ease;
-o-transition: all .8s ease;
transition: all .8s ease;
}

Also, you will need to give the height a specified height instead of "auto" for the transition to take effect.

$('#lm_more').click(function(event){
event.preventDefault();
if($('#description_wrapper').css('height') > '1px') {
    $('#description_wrapper').css({'height': '0px'});
    $('#lm_more').html('Learn More');
}
else {
    $('#description_wrapper').css({'height': '200'});
    $('#lm_more').html('Learn less');
}

});

JS Fiddle

Note that this only works on browsers that support CSS3.

like image 167
Derek Story Avatar answered Sep 28 '22 01:09

Derek Story


Take a look at .slideToggle(), I think this is what you are looking for.

like image 41
Jérôme Avatar answered Sep 28 '22 02:09

Jérôme