Choosing true div height 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 100px. I have a button that displays all the text, basically it does this:

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

this will make the whole text visible, but I would like to animate it. And this will not work with height = 'auto', it must have a certain height.

Question: how do I get the height so that the DIV should show all the text?

+7
jquery html height
source share
3 answers

You can set the height to โ€œautoโ€, then measure it, then set it and trigger 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"); }); });โ€‹ 
+8
source share

try scrollHeight as follows:

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

Note [0] , since this is a property of DOM elements.

+13
source share

TJ Crowder's answer didnโ€™t work for me, because "oldHeight" was a calculated pixel value different from the rem value that I specified in my stylesheet. In addition, the inline style overloaded a different height that I had for another media query. Thus, instead of saving "oldHeight" and then returning it, I just cleared the jQuery inline style by setting css 'height' to an empty string.

 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() { // Measure after var newHeight = div.height('auto').height(); // Remove inline styles div.css('height', ''); div.animate({height: newHeight + "px"}, "slow"); }); });โ€‹ 
0
source share

All Articles