Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animated height adjustment when innerHTML changes

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?

like image 604
Pieter Avatar asked Nov 15 '22 07:11

Pieter


1 Answers

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);
like image 102
Brian Flanagan Avatar answered Jan 04 '23 11:01

Brian Flanagan