Detecting presence of a scroll bar in a DIV using jQuery?

34,512

Solution 1

Assuming overflow on the div is auto:

var div= document.getElementById('something'); // need real DOM Node, not jQuery wrapper
var hasVerticalScrollbar= div.scrollHeight>div.clientHeight;
var hasHorizontalScrollbar= div.scrollWidth>div.clientWidth;

Solution 2

// plugtrade.com - jQuery detect vertical scrollbar function //
(function($) {
    $.fn.has_scrollbar = function() {
        var divnode = this.get(0);
        if(divnode.scrollHeight > divnode.clientHeight)
            return true;
    }
})(jQuery);

example:

if($('#mydiv').has_scrollbar()) { /* do something */ } 
Share:
34,512

Related videos on Youtube

7wp
Author by

7wp

Twitter: 7wp

Updated on July 09, 2022

Comments

  • 7wp
    7wp almost 2 years

    I want to detect the presence of a scroll bar in a DIV using jQuery. I was thinking to use $('div').scrollTop() but that returns 0 in both cases when the scroll bar is at the top and when there is no scroll bar at all.

    Any ideas guys?

  • Justin Johnson
    Justin Johnson about 14 years
    Did you try bobince's solution? His seems like it would work without the extra wrapper div.
  • moi_meme
    moi_meme about 14 years
    wasn't that the answer from the second link i posted? stackoverflow.com/questions/2059743/…
  • 7wp
    7wp about 14 years
    This works too. Thanks. But unlike in my solution example I posted, In the real world I don't have "IDs" to work with, i am selecting the DIV using jQuery CSS selectors...
  • 7wp
    7wp about 14 years
    Yes bobince's solution would work, but unlike in the example i gave above I don't actually have "IDs" to work with. I'm selecting using jQuery CSS selectors, so I can't use getElementById in order to access clientHeight(). plus I dont trust the raw .clientHeight value as I think it returns slightly different numbers in different browsers, doesen't it?
  • BalusC
    BalusC about 14 years
    Then use jQueryElement.get(0) to get the real DOM node from it api.jquery.com/get.
  • Dan Diplo
    Dan Diplo about 14 years
    Whilst this is really useful, is it really the correct answer since it doesn't use any jQuery at all?
  • William Clemens
    William Clemens almost 12 years
    @DanDiplo Remember jQuery is just a JavaScript Library. I'm sure someone could/has written a jQuery plug-in to do the comparison above. But do you really think that level of abstraction is needed?
  • Dan Diplo
    Dan Diplo almost 12 years
    @WilliamClemens Personally, no, but that is what the OP asked!
  • carrabino
    carrabino about 10 years
    Great solution compared to the many other examples/attempts to address this issue. I confirmed that this works on IE, FF and Chrome.
  • Alex
    Alex over 9 years
    I don't understand, my page got a v scrollbar, but the var hasVerticalScrollbar is always false. For sure I declared div as to be the DOM tag I want.