This function will return any document’s height. It’s been tested in IE6/7, FF2/3, Safari (Windows), Google Chrome and Opera 9.5. If the actual document’s body height is less than the viewport height then it will return the viewport height instead:
The Code:
function getDocHeight() { var D = document; return Math.max( D.body.scrollHeight, D.documentElement.scrollHeight, D.body.offsetHeight, D.documentElement.offsetHeight, D.body.clientHeight, D.documentElement.clientHeight ); } |
Usage:
alert( getDocHeight() ); |
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
And for us jQuery junkies:
Actually in jQuery it’s a bit easier because it does most of the work for us:
Any ideas how to get this into the css without flickering… (I believe the height is only known after the page has loaded)..
Nice code though, compliments, greets, Dylan
Excellent!!
Excellent !!! I call the function at the end of my html script and it works just fine. I have successfully tested also on Netscape 9 (Mozilla 5.0), even if I know it is at the end of his life.
Thanks, James. That’s a wonderfully helpful little snippet (especially in jQuery). It just solved an IE6 jqModal overlay nightmare for me.
😉
Great piece of code James – nice,simple and comprehensive. Thanks and loving your work!
Any reason you didn’t use ‘document.height’ tho?
You can pass as many values as you want into Math.max(). Try this:
Thank you for posting this. Surely solves a lot of my presentation issues being able to resize the containers dynamically based on content.
Hi,
thx for this script! It works perfectly with IE 8 and Opera 10, but not with Firefox 3.5. It returns a height of about 30 pixels, even though the document’s height is 1000+ pixel.
Any idea?