WIMB

How to Detect User’s Device Type with JavaScript

Detecting whether a visitor is using a mobile phone, tablet, or desktop computer can help improve the user experience. Whether you want to tailor your layout, load lighter assets, or better understand your audience, JavaScript can offer real-time insights.

Why Detect Device Type?

How It Works

We can use the `navigator.userAgent` property and check for common patterns:


function getDeviceType() {
  const ua = navigator.userAgent;
  if (/mobile/i.test(ua)) return "Mobile";
  if (/tablet/i.test(ua)) return "Tablet";
  return "Desktop";
}
console.log("Device Type:", getDeviceType());
      

Other Techniques

You can also detect screen width or use libraries like Modernizr or WURFL.js for more precise targeting.

Media queries in CSS or `window.innerWidth` in JavaScript can also support responsive strategies.

Related Articles