Accurately determine if element is scrollable
This is probably the safest solution (jQuery required, for plain JavaScript see below):
$.fn.isHScrollable = function () {
return this[0].scrollWidth > this[0].clientWidth;
};
$.fn.isVScrollable = function () {
return this[0].scrollHeight > this[0].clientHeight;
};
$.fn.isScrollable = function () {
return this[0].scrollWidth > this[0].clientWidth || this[0].scrollHeight > this[0].clientHeight;
};
Then you can check if an element is scrollable like this:
$(parent).isScrollable();
For usage without jQuery you can implement functions like this:
function isScrollable(element) {
return element.scrollWidth > element.clientWidth || element.scrollHeight > element.clientHeight;
};
var myParent = document.getElementById('myParent')
isScrollable(myParent)
Do you want to know if an element can ever scroll or can currently scroll?
Can an element ever scroll?
An element can scroll if it has a fixed height
(or max-height
) and overflow-y
is scroll
or auto
. But since it's not easy to tell if an element's height is fixed or not, it's probably sufficient to just check overflow-y
:
e.css('overflow-y') == 'scroll' || e.css('overflow-y') == 'auto'
Can an element scroll right now?
An element can scroll right now if its scrollHeight
is greater than its clientHeight
and if it has a scrollbar, which can be determined by comparing clientWidth
and offsetWidth
(taking margins and borders into account) or checking if overflow-y
is scroll
or auto
.
Merging the two answers together, and adding a little something of my own, this is what I use to check Vertical scrolling. It can be easily converted for other cases. (H & VH)
function isScrollable(e){
if( e.scrollTopMax !== undefined )
return e.scrollTopMax > 0; //All Hail Firefox and it's superior technology!
if( e == document.scrollingElement ) //If what you're checking is BODY (or HTML depending on your css styles)
return e.scrollHeight > e.clientHeight; //This is a special case.
return e.scrollHeight > e.clientHeight && ["scroll", "auto"].indexOf(getComputedStyle(e).overflowY) >= 0
}
I tested this on Firefox, and Chromium. Both Linux. you might still wanna check them for yourself though.