Search code examples
javascriptjqueryjquery-load

jQuery animate on property change


I have I div or some other element which I load content into with:

$('#my_div').load('ajax.php',function(){
    //Do random stuff.
}

However the height of the div will then change, causing the page to jump up and down, looking ugly.

Is there a way for it to animate the height when the new content is loaded or changed? I know one can do this with FluidMoveBehavior in C#.

How can I achieve the same effect with Javascript/jQuery?


Solution

  • Here's some Fiddle

    When you want to create a height or width animation with jQuery you have to set a number indicating the desired size. I assume that you use height: auto in this case so you have to find a little workarround.

    1. Get the height:

      var autoHeight = $("#content").height("auto").height();
      
    2. Animate to autoHeight:

      $("#content").animate({height: autoHeight}, 1000); 
      

    And together:

       var currentHeight = $("#content").height();
       var autoHeight = $("#content").height("auto").height();
       $("#content").height(currentHeight);
       $("#content").animate({height: autoHeight}, 1000); 
    

    Stolen from here