Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript / jQuery : get height when max-height is set to 0

Is it possible to get css value of attr height of element when it's max-height is set to 0?

I need this to know how much pixels of element to show onclick and since every element has different height that changes with size of the browser I want to get height values from css file.

http://jsfiddle.net/AqAJc/

like image 354
vlad Avatar asked Aug 06 '13 14:08

vlad


3 Answers

You can get the height of an element if you have max-height = 0 through the scrollHeight attribute. It works if you set min-weight, but not height though.

HTML :

<div>
  Here you have a normal div
  <div id="toggable">
    Something hidden is in here, but we can still get the height !
    <div class="other-content">
      Something else here
    </div>
  </div>
</div>

JS:

alert(document.getElementById('toggable').scrollHeight)

CSS : #toggable { max-height:0; overflow:hidden; }

.other-content {
  min-height: 100px;
}

Demo : https://jsfiddle.net/asywL84u/2/

Reference : https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

like image 119
Mijamo Avatar answered Sep 28 '22 09:09

Mijamo


My first question would to be why are you using max-height: 0; is there something else you can use? Like hide() show() which use display: none

the only thing I can thing of would be to remove the max-height css get the height and then reapply the max-height:

$('.div').css('max-height', 'none')
console.log($('.div').height())
$('.div').css('max-height', '0')

This should happen fast enough that you wont see the element but it could be wise to hide it before removing the max-height with:

$('.div').hide()
$('.div').css('max-height', 'none')    
console.log($('.div').height())
$('.div').css('max-height', '0')
$('.div').show()
like image 22
Declan Cook Avatar answered Sep 28 '22 07:09

Declan Cook


$('.div').each(function(){
    var t=$(this); // Cache jQuery reference
    t.css('max-height','none'); // Temporarily override max-height
    t.data('height',t.height()); // Store height in data
    t.css('max-height',''); // Remove our max-height override
});
alert($('.div').data('height'));

jsfiddle: http://jsfiddle.net/AqAJc/7/

like image 33
Robert McKee Avatar answered Sep 28 '22 09:09

Robert McKee