Detect mobile/touch

What are the best modern ways to detect mobile and touch? I know: 1. const isTouchDevice = 'ontouchstart' in window; for JS 2. @media (hover: none) and (pointer: coarse) for CSS
11 Replies
ἔρως
ἔρως2w ago
depends on what you want, the media query might be more accurate and you can use it in js however, the js solution you show doesn't do what you think it does: it just checks if the key 'ontouchstart' exists in the window object it doesn't detect if touch is or isn't available
MC23
MC23OP2w ago
Hmm I only tested it Chrome dev tools and it seemed to work, I found an upgraded version that includes || navigator.maxTouchPoints; I'm focusing on detecting touch
ἔρως
ἔρως2w ago
why?
MC23
MC23OP2w ago
https://byteshaman.github.io/favorite-albums-showcase/ I wanna improve the behaviour on this page: on desktop it's hover to show album info and click to visit url, on mobile (or any device with touch) I'd like to show overlay with first touch and then display a visit icon; therefore I wanna apply different logic based on input type Also I know this might not be ideal, I'm just practising arguments that come to my mind along with learning new Angular 18/19 syntax
ἔρως
ἔρως2w ago
what if it is a laptop with touch?
MC23
MC23OP2w ago
It must work like the mobile version, if the user uses touch Basically the cover should be, in both cases, showing the overlay only when "interacted with"
ἔρως
ἔρως2w ago
well, there's a way to do it in pure css, but you need a repeated button it's not the best way, but it works let me show it wait, might not work, afterall
MC23
MC23OP2w ago
Don't worry too much, just link me some stuff to read and I'll try it myself :) I don't wanna take you too much time
ἔρως
ἔρως2w ago
i dont have any example i never had to search for something like this
MC23
MC23OP2w ago
Okay don't worry, it seems to work and I'll pusblish it and do some tests on my mobile
ἔρως
ἔρως2w ago
as long as it works

Did you find this page helpful?