views:

53

answers:

1

I had this idea... let's say I have a DIV that contains some text.

<div id="myDIV">Testing testing lorem ipsum</div>

If I change the content of this DIV by doing something like

$("div#myDIV").html("New text New text New text New text New text New " +
  "text New text New text New text New text New text New text New text " +
  "New text New text New text New text")

the height of the DIV will change.

Is it possible to animate this sudden height change to smoothen the transition?

+1  A: 

It ain't pretty, but this may be a solution. The idea is to wrap your content div with another div that acts as a mask. This way, the inner div's height can be calculated after it's been updated and the animation can be applied to the mask:

// Get current height of container div.
var containerHeight = $('#container').outerHeight();

// Manually set height of container div.
$('#container').css({height: containerHeight});

// Update the html of the content div.
$('#container div').html('New text New text New text New text New text New ' +
     'text New text New text New text New text New text New text New text ' +
     'New text New text New text New text');

// Get the height of the content div.
var contentHeight = $('#container div').outerHeight();

// Animate the height of the container div to the content height.
$('#container').animate({height:contentHeight}, 1000);
Brian Flanagan
I tried it out here: http://jsfiddle.net/zSUfa/2/ I expected "Other content" to be pushed down after the execution of `$('#container').css({height: containerHeight});` (which would be unwanted behavior), but that didn't happen. Why doesn't the enlarged container push "Other content" down prematurely like I expected?
Pieter
In this script, you're animating the height of the container node. It will "push" the 'paragraph node (which is a block element by default - just like the div's) down during the animation. What you're seeing is simply the browser doing what it's supposed to do.
Brian Flanagan
Oh, I get it now... I read your code wrong. But it works, so thanks!
Pieter