On a web page, I need to test if there is a horizontal scrollbar or not (so that I programmatically change the css of some other element). Is there some way to get that information using jquery (or pure javascript)?
I tested
function isHorizontalScrollbarEnabled() {
return $(document).width()!=$(window).width();
}
but it does not seem to work with all browsers (does not work for example with a recent Samsung phone I tested). I need it to work with all browsers, including recent mobile devices.
Thank you!
EDIT 1
I tested the solutions provided by plalx and laconbass, tested IE8, Firefox, Chrome and iPad. Works with IE, Firefox & Chrome but not as I want on the iPad.
The problem seems related to the zooming feature on mobile devices: even though, when I zoom in on the iPad, a horizontal scrollbar appears, document
, window
and document.body
widths do not change (was also the same problem with the Samsung phone I tested earlier today).
Here is the code I used to test:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<title>test</title>
</head>
<body>
<div style="width: 500px; background: red;" id="test">click here to test</div>
<script type="text/javascript">
var i = 1;
$("#test").click(function(){
$(this).html("Test #" + (i++)
+ "<br>document width=" + $(document).width() + ", windows width=" + $(window).width()
+ "<br>document width=" + $(document).width() + ", body width=" + $(document.body).width()
);
});
</script>
</body>
</html>
Any idea how to detect the presence of a horizontal scrollbar that also works after zooming in/out on a mobile device like iPad?