Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get page height in JS (Cross-Browser)

Tags:

javascript

What is the best way to get the actual page (not window) height in JS that is cross-browser compatible?

I've seen a few ways but they all return different values...

self.innerHeight or document.documentElement.clientHeight or document.body.clientHeight or something else?

One way of doing it which seems to work is :

var body = document.body,
    html = document.documentElement;

var height = Math.max( body.scrollHeight, body.offsetHeight, 
                       html.clientHeight, html.scrollHeight, html.offsetHeight );
like image 336
Boris Bachovski Avatar asked Feb 24 '12 11:02

Boris Bachovski


2 Answers

Page/Document height is currently subject to vendor (IE/Moz/Apple/...) implementation and does not have a standard and consistent result cross-browser.

Looking at JQuery .height() method;

if ( jQuery.isWindow( elem ) ) {
            // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
            // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
            var docElemProp = elem.document.documentElement[ "client" + name ],
                body = elem.document.body;
            return elem.document.compatMode === "CSS1Compat" && docElemProp ||
                body && body[ "client" + name ] || docElemProp;

        // Get document width or height
        } else if ( elem.nodeType === 9 ) {
            // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
            return Math.max(
                elem.documentElement["client" + name],
                elem.body["scroll" + name], elem.documentElement["scroll" + name],
                elem.body["offset" + name], elem.documentElement["offset" + name]
            );

nodeType === 9 mean DOCUMENT_NODE : http://www.javascriptkit.com/domref/nodetype.shtml so no JQuery code solution should looks like:

var height = Math.max(
                    elem.documentElement.clientHeight,
                    elem.body.scrollHeight, elem.documentElement.scrollHeight,
                    elem.body.offsetHeight, elem.documentElement.offsetHeight)
like image 140
Krilivye Avatar answered Nov 05 '22 13:11

Krilivye


var width = window.innerWidth ||
            html.clientWidth  ||
            body.clientWidth  ||
            screen.availWidth;

var height = window.innerHeight ||
             html.clientHeight  ||
             body.clientHeight  ||
             screen.availHeight;

Should be a nice & clean way to accomplish it.

like image 21
Jonas Avatar answered Nov 05 '22 12:11

Jonas