I needed to determine if a device is touch enabled or not to modify the user experience based on that. I know that Modernizer is the standard for this sort of thing, and I’ve used it in the past and it does work nicely. However I didn’t want to go that route for two reasons:
- In designing a mobile friendly, fast loading site, I didn’t want to add another library for my users to download when I only needed one feature (that turned out to be one short line of code)
- In my research, Modernizer has limitations with IE10. Now in fairness, the posts I was reading were about two years old and I’m guessing Modernizer has corrected that issue, but given my first point here I didn’t want to go that route anyway.
The Solution
So my solution was this, found via the reference linked below.
1 | var isTouch =(('ontouchstart'in window)||(navigator.msMaxTouchPoints >0)); |
The variable isTouch will return true if you are on a touch screen. The
1 | 'ontouchstart'in window |
portion covers most all browsers, where as
1 | navigator.msMaxTouchPoints > 0 |
is specifically looking for IE devices, I believe it’s IE10 and above with the new Windows mobile push that this came about. So this should cover all browsers and devices.
In Use
With that one line of device feature detection in place, I simply add something like this and we are all set to go.
1 2 3 | if( isTouch == false ) { /* Do something that only non-touch devices can benefit from */ } |
Browsers Tested
- Firefox 29.0.1 (Windows 8.1)
- Chrome 34.0.1847.137 m (Windows 8.1)
- IE 11.0.9600.17107 (Windows 8.1)
- IE 10.0.9200.16721 (Windows 7)
- Safari (iPhone 4s iOS 7.1.1)
- Chrome (iPhone 4s iOS 7.1.1)
References
- This is the source of the final solution I found. The answer was by David.
http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript - This article is good to point out that while my solution may be a “good” option, it’s not perfect. It’s a bit of a rant, but a very factual rant so it’s a good read. He does summarize his main point at the end at least ;)
http://www.stucox.com/blog/you-cant-detect-a-touchscreen/