views:

367

answers:

1

I know that detecting scrollbar presence is supposed to be one of those elusive things that we should all have to suffer through. What I've read so far is that you can't really detect scrollbar presence, only use hints in the DOM to know if they may be present, and it can't be done in less than 30 lines of code.

This sounds a little impossible to me now that we're in 2010. Does jQuery have a cross-browser reliable solution that takes care of this and works at least most of the time? Any help please, I'm pulling my hair, half of it is already on the floor.

+3  A: 

Probably not as elegant as you were hoping for but this is an adequate adaption from a script I recently wrote to calculate viewport height.

Logically you'd want to call this function on document ready and window resize.

It also deals with inconsistencies that you'd encounter in Opera (line 2) and IE7 (line 6).

function scrollbar() {
    var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();

    if (jQuery.browser.msie) {
        if(parseInt(jQuery.browser.version) == 7) {
            viewportHeight -= 3;
        }
    }

    if(viewportHeight <= $('#wrapper').height()) {
        return true;
    } else {
        return false;
    }
}
Steve
+1 Nice, but it doesn't take into consideration `overflow: hidden`, which could prevent a scrollbar from appearing.
Pekka
I think it would work as long as `#wrapper` wasn't the element with `overflow: hidden`- say it was wrapped in `#outer-wrapper` and that had `overflow: hidden`; wouldn't `#wrapper`'s height remain the same?
Steve
You could also refactor the last few lines to a 1-liner tertiary like this `return (viewportHeight <= $('#wrapper').height()) ? true : false;` I've tested it though and I still get a false, not sure what's wrong. I think I may be having a javascript/jquery conflict somewhere or I'm calling these functions incorrectly.
donpal
I'd imagine you can even knock the `? true : false` off the end somehow, I couldn't be bothered to check my syntax though. Are you sure your `#wrapper` is taking the full height of it's content? Perhaps you could try a clearfix at the end?
Steve
You can write just `return viewportHeight <= $('#wrapper').height()`, which always returns true or false, because `< > == <= => !=` are boolean operators.
jholster
Yup, you mean `>=` though not `=>` :)
Steve