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 */ }
Related videos on Youtube
Comments
-
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?
-
moi_meme about 14 years
-
moi_meme about 14 years
-
fmsf about 14 years@moi_meme +1 i was searching for that question to post here :p
-
7wp about 14 years@moi_meme that does not work for DIV's only for the entire window. I tried adapting it to a DIV but it doesent appear to work.
-
-
Justin Johnson about 14 yearsDid you try bobince's solution? His seems like it would work without the extra wrapper div.
-
moi_meme about 14 yearswasn't that the answer from the second link i posted? stackoverflow.com/questions/2059743/…
-
7wp about 14 yearsThis 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 about 14 yearsYes 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 about 14 yearsThen use
jQueryElement.get(0)
to get the real DOM node from it api.jquery.com/get. -
Dan Diplo about 14 yearsWhilst this is really useful, is it really the correct answer since it doesn't use any jQuery at all?
-
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 almost 12 years@WilliamClemens Personally, no, but that is what the OP asked!
-
carrabino about 10 yearsGreat solution compared to the many other examples/attempts to address this issue. I confirmed that this works on IE, FF and Chrome.
-
Alex over 9 yearsI 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.