Himanshu P
Himanshu P

Reputation: 9925

Get viewport height excluding horizontal scrollbar?

window.innerHeight gives the height of the viewport including the height of the horizontal scrollbar. Is there a way to find the usable inner-height, i.e. one which does not include the horizontal scrollbar?

I am ideally looking for a pure JS solution, but if there isn't one, jQuery etc is fine too.

Upvotes: 6

Views: 1720

Answers (3)

user10089632
user10089632

Reputation: 5550

What if I told you it's easier than you think (or than you thought back then) document.body.clientWidth;

Upvotes: 1

Hendrik Jan
Hendrik Jan

Reputation: 4908

I found a solution here: scrollbar detection demo (can I place links to other people's website here?)

The following two functions are used:

// check current presence of H & V scrollbars
// @return array [ Boolean, Boolean ]
function getSBLive(w) {
    var d = w.document, c = d.compatMode;
    r = c && /CSS/.test(c) ? d.documentElement : d.body;
    if (typeof w.innerWidth == 'number') {
        return [ w.innerWidth > r.clientWidth, w.innerHeight > r.clientHeight ];
    } else {
        return [ r.scrollWidth > r.clientWidth, r.scrollHeight > r.clientHeight ];
    }
}

// get current H & V scrollbars tickness
// @return array [ Number, Number ]
function getSBSize(w) {
    var d = w.document, b = d.body, r = [ 0, 0 ], t;
    if (b) {
        t = d.createElement('div');
        t.style.cssText = 'position:absolute;overflow:scroll;top:-100px;left:-100px;width:100px;height:100px;';
        b.insertBefore(t, b.firstChild);
        r = [ t.offsetHeight - t.clientHeight, t.offsetWidth - t.clientWidth ];
        b.removeChild(t);
    }
    return r;
}

You can then use these functions to find the window height without scrollbar:

var sbLive = getSBLive(window);
var sbSize = getSBSize(window);

var windowHeightWithoutScrollBar = sbLive[0] ? sbSize[0] : 0;

Upvotes: 1

StackSlave
StackSlave

Reputation: 10627

The jQuery solution is $(window).height();.

Upvotes: 0

Related Questions