jQuery - animate / slide to height: 100%

35.6k views Asked by At

I have a siple code here:

$('.aktualita_sipky').toggle(function() {
    $(this).parent().find('.aktualita_content').animate({ 
        height: "100%",
      }, 1500 );
}, function() {
    $(this).parent().find('.aktualita_content').animate({ 
        height: "120px",
      }, 1500 );
});

Now when I click it as the first 'toggle', it just shows instantly (without the animation), when I click the the second 'toggle', it nicely slides up.

Is there a way to slide it down to 100% with that nice animation?

3

There are 3 answers

1
Jason Grey On

My workaround for this was to add up the heights of the child elements in the div, adding a little bit to account for margins:

function() {
  $('.accordionblock.open').removeClass('open');
  var childrenheight = 0;  $(this).children().each(function() {childrenheight += ($(this).height()*1.2)});
  $(this).animate({height:childrenheight},300).addClass('open');
  }
}
1
karim79 On

Maybe you could do something like:

$height = $(window).height();   // returns height of browser viewport
//Or
$height = $(document).height(); // returns height of HTML document
//Or
$height = $(whatever).height();
$('.aktualita_sipky').toggle(function() {
    $(this).parent().find('.aktualita_content').animate({ 
        height: $height + 'px',
      }, 1500 );
}, function() {
    $(this).parent().find('.aktualita_content').animate({ 
        height: $height + 'px',
      }, 1500 );
});

http://docs.jquery.com/CSS/height

2
user1473247 On

I found this post while looking for a solution myself and Karim79 had the great suggestion of using a variable and the height() function.

For me I don't start with the height at 100% since I have a preset height defined in my stylesheet. So what I do in the function to expand is I make a variable that has a query to steps back to the specific element I want to expand and changes the css height to 100% and return the height to a variable. Then I set the css for the height back (I suppose I could have used to vars told the original preset height as well incase I edit the css in the future) and then run the animation function using the var with height.

function expandAlbum (){
    var fullHeight = jQuery(this).prev('.albumDropdown').css('height' , '100%').height();
    jQuery(this).prev('.albumDropdown').css('height' , '145px');
    jQuery(this).prev('.albumDropdown').animate({'height' : fullHeight}, 1000, function(){jQuery(this).stop();});
    jQuery(this).html('close');
}

I am also not very experienced so forgive sloppy coding.