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?
//scrol 1px to the left
$(document).scrollLeft(1);
if($(document).scrollLeft() != 0){
//there's a scroll bar
}else{
//there's no scrollbar
}
//scroll back to original location
$(document).scrollLeft(0);
This works because JQuery won't be able to scroll the screen if no scrollbar is available
EDIT 2: I got a downvote because this doesn't work for nothing but the page so I built a generic solution based on @Pabs123's answer, only for fun:
function hasScrollX( selector ){
var e = $(selector), fn = 'scrollLeft';
return e[fn](1) && e[fn]() > 0 && e[fn](0) && true;
}
or even
jQuery.fn.hasScrollX = function( ){
var fn = 'scrollLeft';
return this[fn](1) && this[fn]() > 0 && this[fn](0) && true;
}
See it here, and how it can be easily adapted to detect vertical scrollbar presence.
EDIT: Tested & working on chrome and firefox. As jQuery team does the crossbrowsing work, i suggest the use of jQuery rather than native javascript.
I were curious about how to do this in an elegant way than the suggested previously (which actually work)
The following comparison work to me
$(document).width() > $(window).width()
you can see it in action with scroll bar and without it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With