I’m using $(‘#container_div’).load(url) to populate a div via ajax. I would like to animate the height to the height of the returned content but really cant figure out how to achieve this.
I’ve tried using something like this:
$('#main').fadeOut(function() {
$('#main').load(url, function(data) {
var newHeight = $(data).height();
$('#main').animate({height:newHeight}, function() {$('#main').fadeIn();});
});
});
But can see that this is wrong on so many levels. Especially due to the fact that newHeight === undefined.
Can anybody point me in the right direction here? I would be eternally grateful.
Since fadeOut() finishes by hiding the target elements, chances are your #main will be completely hidden by the time your new data is loaded, rendering any animation of height invisible, and therefore pointless.
But you could just use something like
$('#main').show(400)which will animate the element from a size of (0,0) and opacity of 0 to whatever size is allowed by the container and contents and a fully-visible opacity of 1 (and run these animations in parallel, making both of them visible).But assuming you do care more about animating the height than you do about fading, you still have a problem: by the time load() calls its callback, the height of the target element(s) will already be the height of the content (or as close as possible to it). So animating won’t do anything.
I posted a plugin on a previous question that will do what you want, but you’ll need to use $.get() instead of load():
…where showHtml is defined as: