Brandon Wang
Brandon Wang

Reputation: 3931

Total height of the page

I'm trying to get the total height of a page using JavaScript so I can check if the page is long enough to display something, however in my testing I am unable to get the total height of a page.

I've looked around on the Internet but things like this don't seem to be well documented, as all I can find is scrollHeight, which, as I might mention, doesn't work.

Any way to use JavaScript to find it?

Upvotes: 26

Views: 62721

Answers (7)

Josh Stodola
Josh Stodola

Reputation: 82483

Height of entire page...

document.body.offsetHeight

Height of viewport...

var h,
de = document.documentElement;

if (self.innerHeight) {h = window.innerHeight;}
else if (de && de.clientHeight) {h = de.clientHeight;}
else if (document.body) {h = document.body.clientHeight;}

This article may help you.

Upvotes: 3

Andrii Verbytskyi
Andrii Verbytskyi

Reputation: 7631

To find the height of the entire 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);
})();

NOTE: It is working with Iframes.

Enjoy!

Upvotes: 2

redsquare
redsquare

Reputation: 78667

Have you tried $(document).height(); ?

Demo here

Upvotes: 11

cprcrack
cprcrack

Reputation: 19129

document.documentElement.scrollHeight is working ok for me in the latest version of Internet Explorer, Chrome, Firefox and Safari.

Upvotes: 19

mupdyke
mupdyke

Reputation: 127

Perhaps use the position of an element at the bottom of the page, like:

$("#footer").offset().top

Upvotes: 1

Andreas Grech
Andreas Grech

Reputation: 107950

Without a framework:

var _docHeight = (document.height !== undefined) ? document.height : document.body.offsetHeight;
var _docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;

Upvotes: 47

kgiannakakis
kgiannakakis

Reputation: 104178

Have a look at the documentation. One of the supported methods: height, innerHeight, outerHeight may be suitable for you.

Upvotes: 0

Related Questions