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

= The maximum number of supported touch points (for IE)

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻