Device type in js

Detecting device type (mobile or desktop) via JavaScript has always been a challenging task.

However, distinguishing between devices can be crucial for enhancing the user experience, such as when specific features need to be available only on mobile devices or when the UI requires adjustments.

Over time, various approaches have been attempted to obtain this information, but they have generally proven to be either unreliable or unnecessarily complex.

Fortunately, CSS provides a solution with the @media (pointer) media query, which addresses this issue directly. Moreover, it's possible to leverage this information in JavaScript as well.

function detectDevice() {
  if (window.matchMedia("(pointer: fine)").matches) {
    return { deviceType: "desktop", pointerType: "fine" };
  } else if (window.matchMedia("(pointer: coarse)").matches) {
    return { deviceType: "mobile", pointerType: "coarse" };
  } else {
    return { deviceType: "unknown", pointerType: "none" };
  }
}

const { deviceType, pointerType } = detectDevice();  

One of the most useful tools for this problem (and many others!) was https://modernizr.com/.