JackInABottle JackInABottle - 4 months ago 23
Javascript Question

Calculate height according to div's inner text

I've got a PHP loop to create multiple divs which display data from a database.

<?php

foreach($result as $row) {
?>
<div class="container-fluid" id="content-fluid">
<div class="container-update">
<div class="update-group">
<div class="update-header">
<?php echo $row['update_title'] ?>
<div class="update-author">
by <?php echo $row['update_creator'] ?>
</div>
</div>
<div class="update-body">
<?php echo $row['update_text']; ?>
</div>
</div>
</div>
</div>
<?php
}
?>


I made them clickable through jQuery and they do increase in height:

$(document).ready(function() {

$('.update-group').click(function() {

var clicks = $(this).data('clicks');
if(clicks) {
$(this).removeAttr('style');
}
else {
$(this).animate({height: '200px'}, 300);
}
$(this).data("clicks", !clicks);
});
});


Default height is set to a specific value to ensure that all divs are of the same height and overflow is set to hidden. Clicking on them should expand them downwards according to the text inside of it.

Divs of which the text fits just fine, shouldn't be able to expand at all. And divs with an excessive amount of text should expand to a calculated height.

I've set up a jsfiddle program to demonstrate what I mean: https://jsfiddle.net/vz6s9brd/

Answer

Right now it just animates to 200px and back. I think you're looking for something like this:

$('.update-group').click(function() {

  var clicks = $(this).data('clicks');
  if(clicks) {
    $(this).removeAttr('style');
  }
  else {
    var bod = $(this).find('.update-body');
    var head = $(this).find('.update-header');
    var neededHeight = bod.height() + head.height();
    if ($(this).height() < neededHeight) {
        $(this).animate({height: neededHeight + 'px'}, 300);
    }

  }
  $(this).data("clicks", !clicks);
});