Skip to content

Instantly share code, notes, and snippets.

@roydejong
Created January 7, 2019 03:16
Show Gist options
  • Save roydejong/fb021a973160fa3d04d7aaca675a46cf to your computer and use it in GitHub Desktop.
Save roydejong/fb021a973160fa3d04d7aaca675a46cf to your computer and use it in GitHub Desktop.
JavaScript: Detect touch device (react compatible)
function is_touch_device() {
try {
let prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
let mq = function (query) {
return window.matchMedia(query).matches;
};
if (('ontouchstart' in window) || (typeof window.DocumentTouch !== "undefined" && document instanceof window.DocumentTouch)) {
return true;
}
return mq(['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join(''));
} catch (e) {
console.error('(Touch detect failed)', e);
return false;
}
}
@roydejong
Copy link
Author

nb: heartz is an arbitrary string
Modernizr/Modernizr#1814

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment