Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting the true height of a DIV in jQuery

I have a DIV defined with a fixed height:

.w {
  height: 100px;
  overflow: hidden;
}

if I put text in this it will hide everything that goes beyond the 100px. I have a button that shows all text, basically it does this:

$('.w').height('auto');

this will make all text visible, but I would like to animate this. And that won't work with height='auto', it has to have a specific height.

The question: how do I get the height the DIV should be to be able to show all text in it?

like image 550
patrick Avatar asked Oct 08 '10 11:10

patrick


2 Answers

try scrollHeight like this:

$('#ID_OF_DIV')[0].scrollHeight

Note [0], as it is property of DOM elements.

like image 177
TheVillageIdiot Avatar answered Sep 28 '22 06:09

TheVillageIdiot


You could set the height to 'auto', then measure it, then set it back and start the effect.

Something like this (live example):

jQuery(function($) {

  // Div starts with "style='height: 10px; overflow: hidden"
  var div = $('#thediv');

  // On click, animate it to its full natural height
  div.click(function() {
    var oldHeight, newHeight;

    // Measure before and after
    oldHeight = div.height();
    newHeight = div.height('auto').height();

    // Put back the short height (you could grab this first
    div.height(oldHeight);
    div.animate({height: newHeight + "px"}, "slow");
  });  
});​
like image 26
T.J. Crowder Avatar answered Sep 28 '22 04:09

T.J. Crowder