I wrote a jQuery plugin for desktop and mobile devices. I'm wondering if there is a way to detect if a device has touchscreen capabilities using JavaScript. I'm using jquery-mobile.js to detect touch screen events and it works on iOS, Android, etc., but I also want to write a conditional statement based on whether the user's device has a touch screen or not.
Is this possible?
Update 2021
To see old answers: Check history. I decided to start from scratch because it was getting unmanageable when keeping history in posts.
My original answer said it was possible to use the same functions that Modernizr uses, but that is no longer valid because they removed the "touchevents" test in this PR:https://github.com/Modernizr/Modernizr/ pull/2432because this is a confusing topic.
Having said that, this should be a pretty good way to detect if a browser has "touch capabilities":
But for more advanced use cases, people much smarter than me have written about this topic and I recommend reading these:
Update: Before bringing the entire feature detection library into your project, please readblmstr's answerbelow, detecting actual touch support is more complex and Modernizr only covers basic use cases.
Modernizris a lightweight method for detecting various features on any website.
It just adds classes in html elements for each attribute.
You can then easily target these features in CSS and JS. For example:
and JavaScript (jQuery example):