Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to animate height change without known heights?

I want to animate a height change (when i hide/show divs) using jQuery. I found some examples on SO, but I can't get those to work.

Let's say i have a container with some divs in it.

HTML:

<div class="container">
  <div class="first">Show first div</div>
  <div class="second">Show second div</div>
  <div class="item1">
     Some text
  </div>
  <div class="item2">    
     Some multiline<br />text
  </div>
</div>

jQuery:

$('.first').on('click',function(){
  $('.item2').hide();
  $('.item1').show();
});
$('.second').on('click',function(){
  $('.item1').hide();
  $('.item2').show();
});

http://jsfiddle.net/ytW69/2/

When I click the div .first, I want to show the div .item1, when I click the div .second, I want to show the div .item2. The height of these divs differs, which means the size of the container changes when I hide/display the divs.

How can I animate this height change, without knowing the size of any div?

ps. if there is a CSS solution, that would be even better. I don't think it is possible with just CSS tho.

like image 643
RobinvdA Avatar asked Oct 29 '25 16:10

RobinvdA


1 Answers

Using the optional parameter of .show() and .hide(), you can achieve the animation effect that you want. you can pass that parameter as milliseconds too.

Try,

$('.first').on('click',function(){
    $('.item2').hide('slow');
    $('.item1').show('slow');
});
$('.second').on('click',function(){
    $('.item1').hide('slow');
    $('.item2').show('slow');
});

DEMO

like image 148
Rajaprabhu Aravindasamy Avatar answered Oct 31 '25 07:10

Rajaprabhu Aravindasamy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!