Question

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?

Was it helpful?

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

OTHER TIPS

What I do is the opposite. I animate the page to scroll to the top if not already BEFORE I call the load.

So that the top of any new dynamic content is always in view.

I know this isn't the answer you were looking for, but I've found it works best.

You could hide #my_div before the load(), and then slideDown() in the complete function:

$('#my_div').hide().load('ajax.php', function() {
  $(this).slideDown();
});

Or, create a temporary element, hide it, append it, use its height to animate #my_div once the load is complete, and then remove it.

$('<span/>').hide().appendTo('body').load('ajax.php', function(text) {
  $('#my_div').animate({ height: $(this).height() }, '800').html(text);
  $(this).remove();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top