0

I am trying to find a way that tells me if a page has a vertical and horizontal scrollbars but no way is working.
I can't use jQuery.
This is what I done:

function hasVerticalScroll() {
    return document.body.getBoundingClientRect().height >= window.innerHeight;
}

function hasHorizontalScroll() {
    return document.body.getBoundingClientRect().width >= window.innerWidth;
}

I tested this code on a blank page without scrollbars and in a page with scrollbars and I get incorrect results (I get that there is a scrollbar on a page without a scrollbar for example).

Any idea?

Naor
  • 23,465
  • 48
  • 152
  • 268

2 Answers2

0

I think below functions will help you

  function VerticalScrollExist() {
        if (window.innerHeight) {
            return document.body.offsetHeight > innerHeight;
        }
        else {
            return document.documentElement.scrollHeight > document.documentElement.offsetHeight || document.body.scrollHeight > document.body.offsetHeight;
        }
    }

    function HorizontalScrollExist() {
        if (window.innerWidth) {
            return document.body.offsetWidth > innerWidth;
        }
        else {
            return document.documentElement.scrollWidth > document.documentElement.offsetWidth || document.body.scrollWidth > document.body.offsetWidth;
        }
    }
Pragnesh Khalas
  • 2,908
  • 2
  • 13
  • 26
0

Here you can see where I've tried querying several attributes:

With #shell set to greater than viewport size: http://jsfiddle.net/mori57/8t8Dy/5/

With #shell set to below viewport size: http://jsfiddle.net/mori57/8t8Dy/6/

I think I found a key that you could use, at least for the testing of scrolling... as you can see, in cases where #shell is set to a width over the viewport size (window.innerWidth), the body scrollWidth is greater than the width reported by getBoundingClientWidth().width.

(Sorry, Pragnesh, your function does not appear to work in my example, which is included in my testing page on my jsFiddle, too.)

To that end, the following function should work in most cases:

function HasHorizontalScroll(){
     return document.body.scrollWidth > window.innerWidth;
}

Case with content less than the viewport size: http://jsfiddle.net/mori57/8t8Dy/11/

Case with content greater than the viewport size: http://jsfiddle.net/mori57/8t8Dy/12/

Jason M. Batchelor
  • 2,951
  • 16
  • 25