title: Detecting touch devices and detecting 'can hover' with JavaScript in 2020
body: <h2>TL;DR version</h2>
  <p>How to check if the user is on a touch device and/or can hover, using vanilla JavaScript?</p>
  <hr />
  <h2>Elaborated version</h2>
  <p><a href="https://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript">This post</a> here suggest a bazillion different ways to solve this. But it's now 2020 - and a lot has happend across browsers and devices, so I figured I would draw a line in the sand and start a new question. Many of the answers doesn't consider all corner cases:</p>
  <ul>
  <li>Like stylus'es</li>
  <li>Like Apple's magic mouse that (apparently) emulated touch events (I heard of this, I haven't experienced it myself).</li>
  <li>Like the new iPad Pro, which emulates a Macbook Pro's Safari.</li>
  <li>Like if the capability changes, so the user gains/loses the ability to 'touch' (Like when enabling mobile-view with Chrome Developer tools).</li>
  </ul>
  <hr />
  <h3>My findings</h3>
  <p><strong>Don't use <code>window.matchMedia('(any-pointer: XXXXX)').matches</code></strong></p>
  <p>Some answers suggested the 'new and fancy' <code>window.matchMedia</code> with <code>any-pointer: coarse|none|fine</code>. However, - I was in luck that I have an OnePlus 5t. Because that matchMedia didn't work in neither Firefox nor Chrome on my device (false matching). I played around with the A TON, since I would love to have the same CSS-check, so my JavaScript and my CSS corresponded with one-another, ensuring that styles and functionality matched.</p>
  <p><strong>Don't use userAgent matching</strong></p>
  <p>It's not a good idea, since it would require maintaining the userAgent list, every time a new browser comes out. So it's not future-proof to do it this way. Like the iPad Pro-example mentioned earlier.</p>
  <p><strong>Don't use human touch</strong></p>
  <p><a href="https://codeburst.io/the-only-way-to-detect-touch-with-javascript-7791a3346685" rel="nofollow noreferrer">This Code Burst article</a> suggests using human touch instead of detecting device touch. That may be part of the solution. But if I have a menu for touch-users, then I will have to display that straight away, instead of waiting for the user to touch the screen before showing it.</p>