Anubarak Anubarak - 5 months ago 7
Javascript Question

JQuery animate element height after changing content

I want to resize a div element automaticly after Ajax data was loaded into it.
So far I've no problems in making it taller with that

success: function (data) {
var oldSize = $("#DivPreview").height();
$("#DivPreview").html(data.d);
var newSize = $("#DivPreview").height();
$("#DivPreview").height(oldSize).animate({ height: newSize });
}


But that only works the first time, after that
oldSize
and
newSize
are the same not matter what and it doesn't make the
div
smaller
Does anybody know how I can change the
Height
property dynamically in a smooth way?

If that is useful for you to know I want to create some kind of preview/suggestion for new topics just like on this page when you want to create a new question the
"Questions that may already have your answer"
Box

Thank your for help

Answer

Use scrollHeight instead. Height() sets the css value and is therefore not updated the second time. Since height is set on the parent, you need to calculate the size of the contents instead.

function resizeDiv (elements) {
  // This will actually just get the css value (which was set last time)
  var oldSize = $("#DivPreview").height();
  $("#DivPreview").html(elements);
  // Since height is already set, we calculate the size of the contents instead.
  var newSize = $("#DivPreview ul")[0].scrollHeight;
  $("#DivPreview").height(oldSize).animate({ height: newSize });
}

$('#DivLong, #DivShort').click(function(){
  var $el = $(this).html();
  resizeDiv($el);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="DivPreview">
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>  
</div>

<div id="DivShort">
<ul>
  <li>One (click me)</li>
  <li>Two</li>
</ul>  
</div>

<div id="DivLong">
<ul>
  <li>One (click me)</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li>Siz</li>
  <li>Seven</li>
  <li>Eight</li>
  <li>Nine</li>
</ul>  
</div>

See answer below for more info.

jQuery height() not changing on resize