Detect a Touch Screen with JavaScript
If your website includes features that should only be available to devices with a touch screen, or vice-versa where you would like certain features to be disabled on a touch device, JavaScript can help.
You need no external libraries like jQuery or Modernizr.
The following snippet will hide the element with ID as ‘touchOnly’ if the web page is viewed on a device that doesn’t have a touch screen. This should work on all desktop and mobile devices including iOS, Android, Opera, Chrome, IE, Safari and Windows Phone.
function is_touch_device() {
return 'ontouchstart' in window || navigator.MaxTouchPoints > 0 || navigator.msMaxTouchPoints > 0;
}
if (!is_touch_device()) {
document.getElementById('touchOnly').style.display = 'none';
}
Microsoft has stated that starting with Internet Explorer 11, Microsoft vendor prefixed version of this property (msMaxTouchPoints) may be removed and recommends using MaxTouchPoints instead. PS:MaxTouchPoints = The maximum number of supported touch points (for IE)
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory