Answered
In my web application, I need to detect whether or not the device is touch enabled. If it is a touch enabled device, I need to call different code.
if (isTouchScreenDevice) {
// do something
}
How can I detect this in my JavaScript code?
This should help you detect a touch enabled device:
if (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)) {
// is a touch screen
} else {
// is not a touch screen
}
You can use a combination of checking if the "ontouchstart
event exists and if the device contains maxTouchPoints:
function isTouchEnabled() {
return
("ontouchstart" in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0)
}
function detectTouchDevice() {
var result = false;
if (window.PointerEvent && ("maxTouchPoints" in navigator)) {
if (navigator.maxTouchPoints > 0) {
result = true;
}
} else {
if (window.matchMedia && window.matchMedia("(any-pointer:coarse)").matches) {
result = true;
} else if (window.TouchEvent || ("ontouchstart" in window)) {
result = true;
}
}
return result;
}
navigator.maxTouchPoints
.any-pointer:coarse
media feature, which uses window.matchMedia.There may be scenarios where you detect a touch device. But that doesn't mean a user is actually using the touch screen functionality of the device. For example, if a laptop computer has a touch screen but the user is using the keyboard and/or mouse.