3

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.

RobinvdA
  • 1,313
  • 2
  • 13
  • 28

4 Answers4

3

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

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

You can try this:-

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

When you provide string values like fast and slow then .show() becomes an animation method. The .show() method animates the width, height, and opacity of the matched elements simultaneously.

Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49
0

If you want better looking effect (in my opinion), you can use slideDown() and slideUp():

$('.first').on('click', function () {
    $('.item1:hidden').slideDown('slow');
    $('.item2:visible').slideUp('slow');
});

$('.second').on('click', function () {
    $('.item2:hidden').slideDown('slow');
    $('.item1:visible').slideUp('slow');
});

Check this JSFiddle demo for result.

Pavel Štěrba
  • 2,822
  • 2
  • 28
  • 50
0

The CSS solution that you are looking for is playing with max-height and/or min-height. this might help: css3 height transition on an absolute positioned div to overflow auto fails

Community
  • 1
  • 1
Mabedan
  • 857
  • 8
  • 30
  • I came across some solutions which used max/min-height. However my pages can't have a height, not even a max-height – RobinvdA Feb 19 '14 at 13:28