Is there a simple JavaScript solution for this that is device- and library agnostic?
I'd like to add a class to the html element so I can deliver scrollable containers to mobile when possible.
This would be a similar approach that Modernizr takes, detecting feature support instead of browser detection. I just don't want to use the whole Modernizr framework. Trying to keep the JavaScript light for a mobile project.
Thanks!
Its not perfect but I am using this to detect -webkit-overflow-scrolling.
var overflowScrolling = typeof($("body")[0].style["-webkit-overflow-scrolling"]) !== "undefined";
Then I say if not overflow-scrolling
and mobile then I load iScroll.
It means that devices that support overflow: scroll
but not -webkit-overflow-scrolling
will still load iScroll but this at least gives native scrolling to iOS 5 and modern android.
Here's a solution that checks for all possible options, including non-vendor prefixed properties and doesn't have any dependencies on libraries like jQuery or Modernizr:
function hasOverflowScrolling() {
var prefixes = ['webkit', 'moz', 'o', 'ms'];
var div = document.createElement('div');
var body = document.getElementsByTagName('body')[0];
var hasIt = false;
body.appendChild(div);
for (var i = 0; i < prefixes.length; i++) {
var prefix = prefixes[i];
div.style[prefix + 'OverflowScrolling'] = 'touch';
}
// And the non-prefixed property
div.style.overflowScrolling = 'touch';
// Now check the properties
var computedStyle = window.getComputedStyle(div);
// First non-prefixed
hasIt = !!computedStyle.overflowScrolling;
// Now prefixed...
for (var i = 0; i < prefixes.length; i++) {
var prefix = prefixes[i];
if (!!computedStyle[prefix + 'OverflowScrolling']) {
hasIt = true;
break;
}
}
// Cleanup old div elements
div.parentNode.removeChild(div);
return hasIt;
}
alert(hasOverflowScrolling());
This is a very good question. Unfortunately, currently there seems to be no way to reliably check for overflow: scroll
support.
Filament group has a polyfill for this which you may want to use in your projects (see http://filamentgroup.github.io/Overthrow/), but according to themselves:
The trouble is, it's hard – perhaps impossible – to test for overflow support [...]
Out of necessity, Overthrow examines the user agent string to whitelist the current and future versions of mobile platforms that are known to have native overflow support, but not before checking through more reliable and agnostic means: namely, iOS5's (and now Chrome Android's too!) touch scrolling CSS property, and a broad desktop browser inference test (no touch event support with a screen greater than 1200px wide)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With