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/2432 because this is a confusing topic.
Having said that, this should be a pretty good way to detect if a browser has "touch capabilities":
function isTouchDevice() { return (('ontouchstart' in window) || (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0)); }
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 read below, detecting actual touch support is more complex and Modernizr only covers basic use cases.
Modernizr is 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:
html.touch div { width: 480px; } html.no-touch div { width: auto; }
and JavaScript (jQuery example):
$('html.touch #popup').hide();