I just want to check if the decive, which is using my website, is on a mobile or any other device. It's a quick question with a quick answer I hope.
If you are trying to see if the user's device is mobile, the MDN docs advices to look for the property maxTouchPoints in the navigator (or browser) object and see if the value is > 0.
In the past this used to be done with User Agent Sniffing (Read more here), i.e going through the user-agent header sent by the browser into the navigator.userAgent property to see if it contains certain keywords. This method however has limitations and may not always tell the right kind of device the user is on because many devices today support different browsers and features and vice versa.
var hasTouchScreen = false;
var UA = navigator.userAgent;
hasTouchScreen = (
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
);
if (hasTouchScreen) {
// Device is likely mobile, so do stuff for mobile devices here.
}
maxTouchPoints property and if > 0 in navigator object (MDN Docs Recommended)var hasTouchScreen = false;
if ("maxTouchPoints" in navigator) {
hasTouchScreen = navigator.maxTouchPoints > 0;
}
if (hasTouchScreen) {
// Device is likely mobile, so do stuff for mobile devices here.
}
Be aware, that not all browsers may support that specification, so the navigator object may not have the property maxTouchPoints or some mobile devices may have large screens and some desktop devices may have small touch-screens or some people may use smart TVs and so on. So a better way to do this check would be to combine the snippet above with some fallbacks:
var hasTouchScreen = false;
if ("maxTouchPoints" in navigator) {
hasTouchScreen = navigator.maxTouchPoints > 0;
} else if ("msMaxTouchPoints" in navigator) {
hasTouchScreen = navigator.msMaxTouchPoints > 0;
} else {
var mQ = window.matchMedia && matchMedia("(pointer:coarse)");
if (mQ && mQ.media === "(pointer:coarse)") {
hasTouchScreen = !!mQ.matches;
} else if ('orientation' in window) {
hasTouchScreen = true; // deprecated, but good fallback
} else {
// Only as a last resort, fall back to user agent sniffing
var UA = navigator.userAgent;
hasTouchScreen = (
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
);
}
}
if (hasTouchScreen)
// Do something here.
}
Read more about browser detection using the user agent and the recommended way for mobile device detection here (For the recommended method for mobile device detection, look under the "Mobile device detection" subheading).