Test if page has a horizontal scrollbar (computer & mobile devices)

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 16:14:23
//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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!