Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  178] [ 5]  / answers: 1 / hits: 124061  / 14 Years ago, wed, february 2, 2011, 12:00:00

What's the fastest way of checking whether an element has scroll bars?



One thing of course is checking whether element is larger than its viewport, which can easily be done by checking these two values:



el.scrollHeight > el.offsetHeight || el.scrollWidth > el.offsetWidth


but that doesn't mean that it has scrollbars as well (so it can actually be scrolled by humans).



Question



How do I check for scrollbars in a 1 cross browser and 2 javascript only (as in no jQuery) way?



Javascript only, because I need as small overhead as possible, because I'd like to write a very fast jQuery selector filter



// check for specific scrollbars
$(:scrollable(x/y/both))

// check for ANY scrollbar
$(:scrollable)


I suppose I'd have to check for overflow style settings but how do I do that in a cross browser way?



Additional edit



Not only overflow style settings. Checking whether an element has a scrollbar isn't as trivial as it seems. The first formula I've written above works fine when element doesn't have a border, but when it does (especially when border is of considerable width), offset dimension can be larger than scroll dimension but the element can still be scrollable. We actually have to subtract borders from offset dimension to get the actual scrollable viewport of the element and compare that to scroll dimension.



For future reference



:scrollable jQuery selector filter is included in my .scrollintoview() jQuery plugin. Complete code can be found in my blog post if anybody needs it. Even though it didn't provide the actual solution Soumya's code considerably helped me solve the problem. It pointed me in the right direction.


More From » dom

 Answers
22

I found this somewhere a couple of weeks ago. It worked for me.



var div = document.getElementById('container_div_id');

var hasHorizontalScrollbar = div.scrollWidth > div.clientWidth;
var hasVerticalScrollbar = div.scrollHeight > div.clientHeight;

/* you'll get true/false */

[#93927] Tuesday, February 1, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
annaw

Total Points: 18
Total Questions: 91
Total Answers: 98

Location: Guam
Member since Fri, Jun 18, 2021
3 Years ago
;