There are a lot of ways to detect touchscreen devices with JavaScript. Here are my favorites:
function isTouchDevice(){
return (typeof(window.ontouchstart) != 'undefined') ? true : false;
} |
function isTouchDevice(){
return (typeof(window.ontouchstart) != 'undefined') ? true : false;
}
function isTouchDevice(){
return ('ontouchstart' in window) ? true : false;
} |
function isTouchDevice(){
return ('ontouchstart' in window) ? true : false;
}
function isTouchDevice(){
return 'ontouchstart' in window;
} |
function isTouchDevice(){
return 'ontouchstart' in window;
}
Execution:
if(isTouchDevice())
alert('Touch me!');
else
alert('Click me!'); |
if(isTouchDevice())
alert('Touch me!');
else
alert('Click me!');
Please note: Windows Phone 7 does not support touch events that’s why you should do this:
function isTouchDevice(){
if(navigator.userAgent.match('Windows Phone')){
return true;
}else{
return 'ontouchstart' in window;
}
} |
function isTouchDevice(){
if(navigator.userAgent.match('Windows Phone')){
return true;
}else{
return 'ontouchstart' in window;
}
}
What I also like is the following approach:
if (window.navigator.msPointerEnabled) {
alert('IE10 / Windows 8 / Touch, pen and mouse');
}
else if('ontouchstart' in window){
alert('touch device');
}
else{
alert('mouse device');
} |
if (window.navigator.msPointerEnabled) {
alert('IE10 / Windows 8 / Touch, pen and mouse');
}
else if('ontouchstart' in window){
alert('touch device');
}
else{
alert('mouse device');
}