// 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;
}