Animate element to auto height with jQuery

Daniel picture Daniel · Feb 15, 2011 · Viewed 179.4k times · Source

I want to animate a <div> from 200px to auto height. I can’t seem to make it work though. Does anyone know how?

Here’s the code:

$("div:first").click(function(){
  $("#first").animate({
    height: "auto"
  }, 1000 );
});

Answer

David Tang picture David Tang · Feb 15, 2011
  1. Save the current height:

    var curHeight = $('#first').height();
    
  2. Temporarily switch the height to auto:

    $('#first').css('height', 'auto');
    
  3. Get the auto height:

    var autoHeight = $('#first').height();
    
  4. Switch back to curHeight and animate to autoHeight:

    $('#first').height(curHeight).animate({height: autoHeight}, 1000);
    

And together:

var el = $('#first'),
    curHeight = el.height(),
    autoHeight = el.css('height', 'auto').height();
el.height(curHeight).animate({height: autoHeight}, 1000);