Skip to content

Instantly share code, notes, and snippets.

@esedic
Created September 6, 2019 11:34
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save esedic/39a16a7521d42ae205203e3d40dc19f5 to your computer and use it in GitHub Desktop.
Save esedic/39a16a7521d42ae205203e3d40dc19f5 to your computer and use it in GitHub Desktop.
Various JavaScript methods for detecting touch/mobile devices
// Method 1
var isTouchDevice =
(('ontouchstart' in window) ||
(navigator.MaxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
if(!isTouchDevice){
console.log('is not touch');
}else{
console.log('is touch');
}
// Method 2: Not supported by IE
if(window.matchMedia("(pointer: coarse)").matches) {
// touchscreen
}
// Method 3: Modernizer way
function is_touch_device() {
var prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
var mq = function(query) {
return window.matchMedia(query).matches;
}
if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
return true;
}
// include the 'heartz' as a way to have a non matching MQ to help terminate the join
// https://git.io/vznFH
var query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join('');
return mq(query);
}
// Method 4
// Detection logic:
// 1. If Pointer Events are supported, it will just check the navigator.maxTouchPoints property
// 2. If Pointer Events are not supported, it checks the any-pointer:coarse interaction media feature using window.matchMedia.
// 3. Check for Touch Events support
function detectTouchscreen() {
var result = false;
if (window.PointerEvent && ('maxTouchPoints' in navigator)) {
// if Pointer Events are supported, just check maxTouchPoints
if (navigator.maxTouchPoints > 0) {
result = true;
}
} else {
// no Pointer Events...
if (window.matchMedia && window.matchMedia("(any-pointer:coarse)").matches) {
// check for any-pointer:coarse which mostly means touchscreen
result = true;
} else if (window.TouchEvent || ('ontouchstart' in window)) {
// last resort - check for exposed touch events API / event handler
result = true;
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment