Wed 28 Jul

Geeky stuff: Using jQuery to check if scrollbars are available

On desktop web browsers, setting an element’s overflow to scroll (and in some cases auto) will show scrollbars to the user. However, many mobile platforms (including iPhonePodPad and Android) don’t show the scrollbars, so any content “below the fold” in one of these elements is hidden from view.

Eager to figure out a way around this little issue, I asked on Stackoverflow if anyone else had a solution. Apparently not, but Álvaro G. Vicario had an idea. It sounded hacky, but I ran with it anyway. It seems cleaner than browser detection after all.

I use jQuery to create a div and set it’s overflow to scroll (to force scrollbars where they’re available). I then compare the element’s clientWidth (which takes scrollbars into account) to jQuery’s innerWidth (which doesn’t). If the former is smaller than the latter, there would appear to be a scrollbar. I add a class to the html element (in the style of Modernizr): scrollbars if they’re available, or no-scrollbars if not.

/* Check for the existence of scrollbars. They probably won't be there on mobile devices. Requires jQuery. */
function checkForScrollbars() {
	var sbDiv, sbDivCSS;
	/*
		Create a div and set overflow to scroll, position it off-screen
	*/
	sbDiv = $("<div id='sbTest'></div>");
	sbDivCSS = {'width':'150px','height':'150px','overflow':'scroll','position':'absolute','left':'-3000em'};
	$(sbDiv).css(sbDivCSS);
	$(sbDiv).appendTo("body");
	/*
		clientWidth takes scrollbars into account, innerWidth() 
		doesn't, so clientWidth should be smaller if there's a 
		scrollbar. We add a class to <html> accordingly, 
		Modernizr style.
	*/
	if ($(sbDiv)[0].clientWidth < $(sbDiv).innerWidth()) {
		$("html").addClass("scrollbars");
	} else {
		$("html").addClass("no-scrollbars");
	}
	$(sbDiv).remove();
}

In my (admittedly brief) testing, this appears to work on a variety of desktop browsers (Chrome, Safari, Firefox, IE6/7/8), as well as the built-in browser on iOS 3.2 and 4.0, Android 1.6 and a Blackberry.

Please try it for yourself. If you find a situation where it doesn’t work (or you’ve got any other useful feedback) please let me know.