views:

984

answers:

3

Hi,

I just want some simple JQ/JS to check if the current page/window (not a particular element) has a vertical scrollbar.

Googling gives me stuff that seems overly complex for just this basic feature.

How can this be done?

+4  A: 
$(document).ready(function() {
    // Check if body height is higher than window height :)
    if ($("body").height() > $(window).height()) {
        alert("Vertical Scrollbar! D:");
    }

    // Check if body width is higher than window width :)
    if ($("body").width() > $(window).width()) {
        alert("Horizontal Scrollbar! D:<");
    }
});
TiuTalk
+1 but for the sake of exactness, this only checks whether the content expands further than the viewport. If the `overflow` property of the `body` is set to `hidden` somewhere along the line, it won't work. Setting hidden on a body is extremely rare, though.
Pekka
+6  A: 

try this:

var hasVScroll = document.body.scrollHeight > document.body.clientHeight;

This will only tell you if the vertical scrollHeight is bigger than the height of the viewable content, however. The hasVScroll variable will contain true or false.

If you need to do a more thorough check, add the following to the code above:

// Get the computed style of the body element
var cStyle = document.body.currentStyle||window.getComputedStyle(document.body, "");

// Check the overflow and overflowY properties for "auto" and "visible" values
hasVScroll = cStyle.overflow == "visible" 
             || cStyle.overflowY == "visible"
             || (hasVScroll && cStyle.overflow == "auto")
             || (hasVScroll && cStyle.overflowY == "auto");
Andy E
+1 Nice! And with the necessary computed style (which was the point at which I decided not to get involved with this question ;)
Pekka
lol yeah I was debating whether or not to make the extra effort to write it because in many cases it's not needed.
Andy E
Yeah, but it's the only really proper way. Good job!
Pekka
A: 

I tried the previous answer and doesn't seem to be working the $("body").height() is always 0.

I have corrected the solution as follows:

// Check if body height is higher than window height :) 
if ($(document).height() > $(window).height()) { 
    alert("Vertical Scrollbar! D:"); 
} 

// Check if body width is higher than window width :) 
if ($(document).width() > $(window).width()) { 
    alert("Horizontal Scrollbar! D:<"); 
} 
Bharat