436

Some documents I can't get the height of the document (to position something absolutely at the very bottom). Additionally, a padding-bottom on seems to do nothing on these pages, but do on the pages where height will return. Case(s) in point:

http://fandango.com
http://paperbackswap.com

On Fandango
jQuery's $(document).height(); returns correct value
document.height returns 0
document.body.scrollHeight returns 0

On Paperback Swap:
jQuery's $(document).height(); TypeError: $(document) is null
document.height returns an incorrect value
document.body.scrollHeight returns an incorrect value

Note: I have browser level permissions, if there is some trick there.

niton
  • 8,771
  • 21
  • 32
  • 52
Nic
  • 4,621
  • 3
  • 19
  • 12
  • 5
    $(document) is null because that site doesn't have jQuery loaded... – James Jul 17 '09 at 21:57
  • Hm, could have sworn I checked something else to confirm jQuery was registered but it doesn't look like I did, HA! I thought firebug had jQuery packaged... hm, I guess I will check this out then if it's a solution. – Nic Jul 17 '09 at 22:04
  • 4
    firebug does not have jQUery packaged – harsimranb Aug 23 '12 at 02:11
  • See [Finding the size of the browser window](http://www.howtocreate.co.uk/tutorials/javascript/browserwindow). It has a great table of the behaviors of different browsers. – Oriol Jun 30 '15 at 23:56

13 Answers13

786

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.

Community
  • 1
  • 1
Borgar
  • 37,817
  • 5
  • 41
  • 42
  • 2
    rate this solution, because it works when you are using prototype library, with jQuery there is no such issue – se_pavel Sep 29 '09 at 18:28
  • 11
    When working with iframes and jquery, because of this method of calculation, the iframe's document height will allways be at least the height of the iframe itselft. This is important to note when you want to reduce the iframe's height to match the content. You first have to reset the height of the iframe. – David Lay Nov 30 '09 at 13:35
  • 3
    I had the need to grow the iframe and shrink it (facebook app) and found that document.body.offsetHeight was the best choice for me, accurately supported by the most browsers. – ElJeffe Aug 03 '12 at 01:04
  • 1
    This is great although can give incorrect results if the document is not ready - ie, when used in server generated code... – Stuart Dobson Oct 02 '12 at 03:51
  • Yeah.. and how many sites aren't generated these days.. 5%... I keep getting zero for my height. – baash05 Dec 05 '12 at 02:51
  • 1
    Testing the document before it is ready won't work. This has nothing to do with generated code/documents but rather how the document is loaded. The test must run *after* the document is ready, and I would suggest running it only when the document is fully loaded as remaining items may affect the height, also resizing the browser. – Borgar Dec 05 '12 at 13:02
  • What can be done to get the height, when some multimedia files like flash are embedded? Their height does not seem to be included in any of five possibilities you listed. – Tiny Jun 15 '14 at 11:16
  • Amazing! Worked for me. When calculating, you will need to set it to execute this code on a resize event and onload because when the window is resized, the height of the document is likely to change. – www139 Sep 07 '15 at 02:21
  • It seems like this works without issues when used on an iframe, but try to use this on an iframe that is within another frame and you will get wrong results. (and yes, I confirmed it is targetting the inner iframe, though a number that should be 1240, comes back at 877). Any ideas? – NinjaKC May 03 '16 at 16:27
  • 1
    @Borgar You're my hero. Works like a charm. – tiriana Aug 19 '16 at 09:06
  • @Borgar @www139 I am also doing it on `resize` event. But, for me the `contentWindow` is null. Could you please help – Kuldeep Bhimte Feb 21 '19 at 03:22
  • @KuldeepBhimte try adding a timeout on the resize listener for 0 milliseconds. I've found that, sometimes, the browser will fire both onload and resize at the same time when the page loads/renders. This can cause weird problems so that's why I'll generally add a small timeout before firing the first resize event. – www139 Feb 21 '19 at 07:08
  • @www139 , I just tried that, but still gets `null` for `contentDocument` – Kuldeep Bhimte Feb 21 '19 at 07:27
  • @KuldeepBhimte does it work with onload? This might be something to troubleshoot in a chat or make a new post. – www139 Feb 21 '19 at 07:33
  • @www139 I have some other issue with the iframe could you please check here https://stackoverflow.com/questions/54784044/anchor-tags-href-isnt-working-when-iframe-is-opened-in-a-react-dialog-model – Kuldeep Bhimte Feb 21 '19 at 19:22
  • This needs to be edited: Note: body.scrollHeight could have absolute element which could increase "visible scroll/visible full" height of page. If you would like to check "visible full height" of page you should check (element.scrollHeight - element.scrollTop === element.clientHeight) – fearis Jun 03 '19 at 09:36
420

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
GKFX
  • 1,386
  • 1
  • 11
  • 30
M -
  • 26,908
  • 11
  • 49
  • 81
  • 15
    As of 2017 this should be marked as the right answer to me. – Joan Jul 07 '17 at 09:43
  • @Joan That's up to the original poster to decide :) – M - Jul 07 '17 at 18:06
  • 2
    Doesn't work in presence of margins. [`document.documentElement.getBoundingClientRect()`](https://stackoverflow.com/a/47362453/332528) works better. – torvin Nov 18 '17 at 04:20
  • 14
    There is one error with this: Say for example that there is an `

    ` element at the start of the `` with it's default margin, it will push the `` element down without a way to detect it. `document.documentElement.scrollHeight` (not `document.body,scrollHeight`) is the most accurate way of doing things. This works with both body margins and margins of stuff inside the body pushing it downwards.

    – Ethan Feb 13 '18 at 08:25
31

Full Document height calculation:

To be more generic and find the height of any document you could just find the highest DOM Node on current page with a simple recursion:

;(function() {
    var pageHeight = 0;

    function findHighestNode(nodesList) {
        for (var i = nodesList.length - 1; i >= 0; i--) {
            if (nodesList[i].scrollHeight && nodesList[i].clientHeight) {
                var elHeight = Math.max(nodesList[i].scrollHeight, nodesList[i].clientHeight);
                pageHeight = Math.max(elHeight, pageHeight);
            }
            if (nodesList[i].childNodes.length) findHighestNode(nodesList[i].childNodes);
        }
    }

    findHighestNode(document.documentElement.childNodes);

    // The entire page height is found
    console.log('Page height is', pageHeight);
})();

You can Test it on your sample sites (http://fandango.com/ or http://paperbackswap.com/) with pasting this script to a DevTools Console.

NOTE: it is working with Iframes.

Enjoy!

Andrii Verbytskyi
  • 7,155
  • 3
  • 47
  • 38
30

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())
JRodDynamite
  • 12,325
  • 5
  • 43
  • 63
Mimo
  • 6,015
  • 6
  • 36
  • 46
6

The "jQuery method" of determining the document size - query everything, take the highest value, and hope for the best - works in most cases, but not in all of them .

If you really need bullet-proof results for the document size, I'd suggest you use my jQuery.documentSize plugin. Unlike the other methods, it actually tests and evaluates browser behaviour when it is loaded and, based on the result, queries the right property from there on out.

The impact of this one-time test on performance is minimal, and the plugin returns the right results in even the weirdest scenarios - not because I say so, but because a massive, auto-generated test suite actually verifies that it does.

Because the plugin is written in vanilla Javascript, you can use it without jQuery, too.

hashchange
  • 7,029
  • 1
  • 45
  • 41
6

The proper answer for 2017 is:

document.documentElement.getBoundingClientRect().height

Unlike document.body.scrollHeight this method accounts for body margins. It also gives fractional height value, which can be useful in some cases

torvin
  • 6,515
  • 1
  • 37
  • 52
  • 1
    These are the results I get when I try your method on this page: https://i.imgur.com/0psVkIk.png Your method returns something that looks like the window height, while `document.body.scrollHeight` lists the entire scrollable height, which is what the original question asked. – M - Nov 22 '17 at 22:05
  • 2
    @Marquizzo that's because this page has `html { height: 100% }` in css. So the API correctly returns the **real** calculated height. Try removing this style and also adding margins to `body` and you will see what's the problem with using `document.body.scrollHeight`. – torvin Nov 22 '17 at 23:31
  • There is one error with this: Say for example that there is an `

    ` element at the start of the `` with it's default margin, it will push the `` element down without a way to detect it. `document.documentElement.scrollHeight` (not `document.body,scrollHeight`) is the most accurate way of doing things.

    – Ethan Feb 13 '18 at 08:23
  • @Booligoosh not sure what you mean. `documentElement.scrollHeight` gives a wrong value in this case. `documentElement.getBoundingClientRect().height` gives the correct one. check this out: https://jsfiddle.net/fLpqjsxd/ – torvin Feb 13 '18 at 22:57
  • @torvin The .documentElement one works: https://jsfiddle.net/fLpqjsxd/5/ – Ethan Feb 14 '18 at 01:42
  • @Booligoosh as you can see in your fiddle, `documentElement.scrollHeight` only works properly when there is a need for a scroll bar, while `documentElement.getBoundingClientRect().height` works correctly in both cases. – torvin Feb 14 '18 at 06:16
  • Doesn't seem to work on this very page. `document.documentElement.getBoundingClientRect().height` : `1299`. `document.documentElement.scrollHeight` : `9031` `document.body.scrollHeight` : `9031` Also see screenshot here : [![document-document-Element-get-Bounding-Client-Rect-height-shows-wron.png](https://i.postimg.cc/v8nGkfCX/document-document-Element-get-Bounding-Client-Rect-height-shows-wron.png)](https://postimg.cc/qgkfChJC) – Rob Waa May 29 '19 at 16:20
  • @RobWaa see comments above about this very page – torvin May 30 '19 at 02:01
  • 1
    @torvin Fact remains that not the intended result is returned by `getBoundingClientRect().height`. It gets sidetracked, while 3 (three) other methods don't get sidetracked. Including the one that you mention as inferior to it. And you insist on doing so by suggesting to remove 100% from this page's html height, and adding margins to it. What's the point ? Just accept that `getBoundingClientRect().height` is also not bullet-proof. – Rob Waa May 30 '19 at 21:15
  • @RobWaa I suggest to add margins to show that using `scrollHeight` returns incorrect results in this case. The behaviour of `getBoundingClientRect()` makes total sense to me. If it doesn't for you - feel free to use whatever else. – torvin May 31 '19 at 04:45
  • @torvin So this page was only 1299px high, instead of 9031px. :/ Like I commented earlier, none of these methods (4x) is bullet proof. You can't preach that one is more appropriate than the other because it's "for 2017". The fact that your suggested method falters in 2019 is proof of that. No matter how much you try to tarnish the other methods. Better measure with 2 or more of those 4 methods. So first investigate the DOM, then execute the most reliable method. It's somewhat similar to browser capability testing. If you prefer to depend one one method, than go for it. It's your party. – Rob Waa May 31 '19 at 10:54
  • The truth is, "the height of the document" doesn't exist in HTML. You can measure only the height of an element. If your `` has `height=100%` it won't match what you think "the document" is. But it **is** what the browser thinks. – torvin Jun 03 '19 at 11:45
5

I lied, jQuery returns the correct value for both pages $(document).height();... why did I ever doubt it?

Nic
  • 4,621
  • 3
  • 19
  • 12
2

To get the width in a cross browser/device way use:

function getActualWidth() {
    var actualWidth = window.innerWidth ||
                      document.documentElement.clientWidth ||
                      document.body.clientWidth ||
                      document.body.offsetWidth;

    return actualWidth;
}
HumanInDisguise
  • 1,335
  • 4
  • 17
  • 29
user937284
  • 2,454
  • 6
  • 25
  • 29
1

This cross browser code below evaluates all possible heights of the body and html elements and returns the max found:

            var body = document.body;
            var html = document.documentElement;
            var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight); // The max height of the body

A working example:

function getHeight()
{
  var body = document.body;
  var html = document.documentElement; 
  var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight);
  return bodyH;
}

document.getElementById('height').innerText = getHeight();
body,html
{
  height: 3000px;
}

#posbtm
{
  bottom: 0;
  position: fixed;
  background-color: Yellow;
}
<div id="posbtm">The max Height of this document is: <span id="height"></span> px</div>

example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
example document body content example document body content example document body content example document body content <br />
willy wonka
  • 1,440
  • 1
  • 18
  • 31
0

For anyone having trouble scrolling a page on demand, using feature detection, I've come up with this hack to detect which feature to use in an animated scroll.

The issue was both document.body.scrollTop and document.documentElement always returned true in all browsers.

However you can only actually scroll a document with either one or the other. d.body.scrollTop for Safari and document.documentElement for all others according to w3schools (see examples)

element.scrollTop works in all browsers, not so for document level.

    // get and test orig scroll pos in Saf and similar 
    var ORG = d.body.scrollTop; 

    // increment by 1 pixel
    d.body.scrollTop += 1;

    // get new scroll pos in Saf and similar 
    var NEW = d.body.scrollTop;

    if(ORG == NEW){
        // no change, try scroll up instead
        ORG = d.body.scrollTop;
        d.body.scrollTop -= 1;
        NEW = d.body.scrollTop;

        if(ORG == NEW){
            // still no change, use document.documentElement
            cont = dd;
        } else {
            // we measured movement, use document.body
            cont = d.body;
        }
    } else {
        // we measured movement, use document.body
        cont = d.body;
    }
Y.K.
  • 290
  • 2
  • 9
-1

use blow code for compute height + scroll

var dif = document.documentElement.scrollHeight - document.documentElement.clientHeight;

var height = dif + document.documentElement.scrollHeight +"px";
ali bagheri
  • 139
  • 2
  • 5
-4

Add References properly

In my case I was using a ASCX page and the aspx page that contains the ascx control is not using the references properly. I just pasted the following code and it worked :

<script src="../js/jquery-1.3.2-vsdoc.js" type="text/javascript"></script>
<script src="../js/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../js/jquery-1.5.1.js" type="text/javascript"></script>
IAmInPLS
  • 4,051
  • 4
  • 24
  • 57
Tosh
  • 531
  • 7
  • 3
-5

I don't know about determining height just now, but you can use this to put something on the bottom:

<html>
<head>
<title>CSS bottom test</title>
<style>
.bottom {
  position: absolute;
  bottom: 1em;
  left: 1em;
}
</style>
</head>

<body>

<p>regular body stuff.</p>

<div class='bottom'>on the bottom</div>

</body>
</html>
jedihawk
  • 814
  • 1
  • 12
  • 12
  • 1
    Trust me, I have exhausted HTML and CSS resources on this one. Can't explain it but you will see the issues if you try this on those sites. – Nic Jul 17 '09 at 22:09