Skip to content

Instantly share code, notes, and snippets.

Created January 7, 2019 03:16
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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;
Copy link

nb: heartz is an arbitrary string

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