How to get height of entire document with JavaScript?
This is a really old question, and thus, has many outdated answers. As of 2020 all major browsers have adhered to the standard.
Answer for 2020:
document.body.scrollHeight
Edit: the above doesn't take margins on the <body>
tag into account. If your body has margins, use:
document.documentElement.scrollHeight
You can even use this:
var B = document.body,
H = document.documentElement,
height
if (typeof document.height !== 'undefined') {
height = document.height // For webkit browsers
} else {
height = Math.max( B.scrollHeight, B.offsetHeight,H.clientHeight, H.scrollHeight, H.offsetHeight );
}
or in a more jQuery way (since as you said jQuery doesn't lie) :)
Math.max($(document).height(), $(window).height())
Document sizes are a browser compatibility nightmare because, although all browsers expose clientHeight and scrollHeight properties, they don't all agree how the values are calculated.
There used to be a complex best-practice formula around for how you tested for correct height/width. This involved using document.documentElement properties if available or falling back on document properties and so on.
The simplest way to get correct height is to get all height values found on document, or documentElement, and use the highest one. This is basically what jQuery does:
var body = document.body,
html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
A quick test with Firebug + jQuery bookmarklet returns the correct height for both cited pages, and so does the code example.
Note that testing the height of the document before the document is ready will always result in a 0. Also, if you load more stuff in, or the user resizes the window, you may need to re-test. Use onload
or a document ready event if you need this at load time, otherwise just test whenever you need the number.