Check if the page has a horizontal scrollbar (computer and mobile devices)

On the webpage, I need to check if there is a horizontal scrollbar or not (so I programmatically change the css of some other element). Is there any way to get this information using jquery (or pure javascript)?

I tested

function isHorizontalScrollbarEnabled() {
    return $(document).width()!=$(window).width();
}

but it doesn't seem to work with all browsers (for example, it doesn’t work with the latest Samsung phone that I tested). I need it to work with all browsers, including the latest mobile devices.

Thank!

EDIT 1

I tested the solutions provided by plalx and laconbass, tested IE8, Firefox, Chrome and iPad. Works with IE, Firefox, and Chrome, but not the way I want on an iPad.

: , , iPad, , document, window document.body ( Samsung, ).

, :

<!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>

, , / , iPad?

+5
2
//scrol 1px to the left
$(document).scrollLeft(1);

if($(document).scrollLeft() != 0){
   //there a scroll bar
}else{
   //there no scrollbar
}

//scroll back to original location
$(document).scrollLeft(0);

, JQuery ,

+7

2: , , , @Pabs123, :

function hasScrollX( selector ){
    var e = $(selector), fn = 'scrollLeft';
    return e[fn](1) && e[fn]() > 0 && e[fn](0) && true;
}

jQuery.fn.hasScrollX = function( ){
    var fn = 'scrollLeft';
    return this[fn](1) && this[fn]() > 0 && this[fn](0) && true;
}

.

EDIT. firefox. jQuery , jQuery, javascript.

, , ( )

$(document).width() > $(window).width()

+3

All Articles