tags:

views:

16

answers:

2

I have a DIV defined with a fixed height. Like this:

.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?

+2  A: 

try scrollHeight like this:

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

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

TheVillageIdiot
Seems to work: http://jsbin.com/ecoda/5
T.J. Crowder
ok, this works indeed! is this array documented somewhere? I would never have guess this! ;-)
patrick
@patrick: *"is this array document somewhere?"* Yes, here's the link: http://docs.jquery.com/Types#jQuery A jQuery instance is (amongst other things) a pseudo-array of the DOM elements that are in the current set. So `var jqobj = $('#foo');` gives you a jQuery instance for the element with the ID "foo" (if any). You can access the raw element via `jqobj[0]`, and the number of matched elements via `jqobj.length`. **Unlike** a real array, you should treat the `length` property and the element entries as read-only. (cont'd)
T.J. Crowder
(continuing) ..as read-only. Never do `jqobj.length = 3;` for instance, or `jqobj[0] = someElement;` (though you can do what you like, within reason, with the actual element at `jqobj[0]`). Always modify the contents of the jQuery instance via jQuery function calls. But accessing the raw DOM elements is documented and supported.
T.J. Crowder
+1  A: 

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");
  });  
});​
T.J. Crowder
div.height('auto').height() seems to work great! thanks for this solution. I think it's a bit more elegant than the div[0].scrollheight. Makes it more readable
patrick