As of 5/5/2022:
var isTouch = "maxTouchPoints" in window.navigator && window.navigator.maxTouchPoints > 1;var isTouchTwo = "ontouchstart" in window;var isTouchThree = window.matchMedia && window.matchMedia("(pointer:coarse)").matches;var isDesktopIE = !!window.MSInputMethodContext && !!document.documentMode && !isTouchTwo;var uaDataIsMobile = window.navigator.userAgentData && window.navigator.userAgentData.mobile;var isDevice = typeof uaDataIsMobile === 'boolean' ? window.navigator.userAgentData.mobile || (isTouchTwo && isTouchThree) : ((/android|avantgo|blackberry|googlebot-mobile|iemobile|opera mini|kitkat|palmos|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|iphone|ipod|phone|ipad|pie|tablet|silk|up\.browser|up\.link|playbook|webos|wos/i.test(window.navigator.userAgent.toLowerCase()) && !isDesktopIE) || window.navigator.platform === 'MacIntel'&& isTouch);console.log('1. '+isTouch+' 2. '+isTouchTwo+' 3. '+isTouchThree+' 4. '+/android|avantgo|blackberry|googlebot-mobile|iemobile|opera mini|kitkat|palmos|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|iphone|ipod|phone|ipad|pie|tablet|silk|up\.browser|up\.link|playbook|webos|wos/i.test(window.navigator.userAgent.toLowerCase())+' 5. isDevice: '+isDevice)
Redresses issues, a) where IE11 desktop navigator.userAgent
string claims to be "tablet", and b) where iPadOS User Agent in Safari is same as on MacOS Catalina. (Untested by me, but it follows this line of argumentation
quote
https://developer.apple.com/forums/thread/119186
unquote
and should work. I'm depending on it. (See edit.)
Note that my answer is compatible with Client Hints. (Future answers should also be, I think.) For browsers that support navigator.userAgentData
, you won't need navigator.userAgent
.
Sorry about the long strings. In ES6 it looks prettier.
To do a media query, just attach a style sheet based on true or false output.
edit: How to detect iPad and iPad OS version in iOS 13 and Up?
if (navigator.maxTouchPoints > 1) { // browser supports multi-touch}
I thought it was > 0
. (Corrected in code.)