I'm working on a web app and need to figure out if the user is on a touch device or a non-touch one. Initially, I thought of using events like `touchstart` to set a variable `isTouch` to true, and `mousedown` to set it to false. But I ran into issues because browsers trigger the mouse events shortly after touch events for compatibility reasons. I found solutions like checking if `ontouchstart` exists in the window, but that doesn't work on all devices that support both touch and mouse inputs. Eventually, I used the CSS pointer media feature, which differentiates between touch and mouse inputs effectively. I also learned about the PointerEvents approach which can detect input types dynamically, but it requires user interaction to initially determine input type. Has anyone else tackled this problem?
2 Answers
I ran into the same issue in my app! Using the PointerEvents is great for detecting whether the device is using a touch, mouse, or even a pen. Just remember to subscribe to the right pointer actions like 'pointerup' instead of 'mouseup'.
That's a solid approach! However, I'm curious about how it works on devices that have both touch and mouse capabilities, like Surface tablets or the Steam Deck with a mouse. Has anyone tested that?
I tried it out on my tablet, and when I use touch, it switches to 'coarse', and if I switch back to the mouse, it goes back to 'fine'. This method worked perfectly for me!
Great tip! I think the only downside here is that you'll have to wait for the user to interact first to know what input method they're using.