JS detect mobile device
BaasMurdo
Posted on July 25, 2022
Hey there all! I guess this is kinda like my Hello world of writing posts, so don't be too harsh π
Disclaimer
I am not claiming this is the best way & I wouldn't call it the most complete way to check if a device is a "popular-ish" mobile device. But it is simple and should work correctly for the most part. (If you do see/find an issue, please feel free to let me know) Last but not least, I did not come up with this. I found it and will share a link here if and when I find the post again.
Introduction
Firstly, if you want to apply styles to something depending on actual screen sizes. (my opinion) Use the built-in CSS media queries, very reliable once you understand them.
The use case for this would be more if you want certain functionality to only trigger on a mobile or a desktop.
Now that I have that out of the way, here is the solution and a minor explanation after.
var agentDetails = navigator.userAgent;
function isMobile() {
if(/Android|Mobi|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(agentDetails) ) {
// Hit here if the device is a "popular-ish" mobile device
} else {
// Hit here if the device is NOT a "popular-ish" mobile device
}
}
Explanation
Ok so let's start dissecting this...
The first line var agentDetails = navigator.userAgent
gets the user agent data for the browser used.
In short, this gets the Platform, Security, OS-or-CPU, Localization, revision-version-number
relavent to the current device. (at time of writing)
This will contain the info we want to see and will be the White text in the Codepen below.
The second important part is the if()
statement. The string in the if()
has a /
at the start and a /i
at the end (the /i
at the end, just makes it case-insensitive) & is delimited by pipes ("|").
This creates a regular expresion of the string. (This could be an entire other series π
)
The reason we make it a regular expression is so that we can use the .test()
method against it which "executes a search for a match between a regular expression and a specified string." you can read more about it here
So if the user agent data returns for instance:
"Mozilla/5.0 (iPad; CPU OS 15 5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"
This would be an iPad, so it would return true as the string we are checking (user agent) & the regular expression both contain the word iPad.
Conclusion
I think that is it, as promised here is the Codepen I created, it's not fancy, it's not pretty, but it works.
As seen in the user agent documentation, this info can be altered by the user or third-party apps. So beware, results may vary.
Posted on July 25, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 2, 2024
September 19, 2024
August 20, 2024