Using either plain Javascript or jQuery, I need to get the full height of a scrolling element. But the DOM property scrollHeight
is apparently not 100% reliable.
I was envisioning temporarily giving the item a css height of auto
, checking out its size, then returning the css to its prior value (which itself has problems--how do I get the css height:100%
instead of height:1012px
like jQuery .css('height')
will return). But then I figured out that due to the way jQuery applies css styling directly to an element, simply applying the style ''
returns it to its normal style-sheet-declared value, so theoretically I could do this:
$el.css('height', 'auto');
scrollHeight = $el.height();
$el.css('height', '');
But this isn't working. height:auto
isn't overriding my element's original style of 100%
and making the element take up its full desired height.
So now I'm thinking something more along these lines: use the position of the first child element's top and the position of the last child element's bottom to get the height. (I can adjust for padding and margin if necessary, this is just a proof of concept.)
function scrollHeight($el) {
var lastEl = $el.children(':last');
return (
lastEl.position().top
+ lastEl.height()
- $el.children(':first').position().top;
);
}
Some working in of Math.max($el[0].scrollHeight, $el.height())
could also be useful...
Is that a terrible idea? I can't be the only person who's ever needed to know the scrollHeight
of a DOM element and have it be reliable, not changing as the item is scrolled, and working in all major browsers, as well as IE 8 (though it would be interesting to know a solution for IE 6 & 7).
Instead of
$el.css('height', 'auto');
Try -
$el.attr('style', 'height: auto !important');
I mention trying this becuase you say -
height:auto isn't overriding my element's original style of 100% and making the element take up its full desired height.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With