November 19, 2011 in Javascript, Programming, Tutorials by admin

Easily detect mobile devices with JavaScript including Android devices, iPhone, iPad, and webOS. Have you ever wanted to display something different for mobile devices or run an alternate effect or function depending on the user agent? With only a few lines of javascript code you can do all of this.

There are many User Agents to detect for when it comes to mobile. I will not be listing them all here but I have including the biggest ones. Below we use a simple JavaScript match() method to take the user agent string and match it against our regular expression which is the device name. I have created variables out of the user agent detection which will return true in a conditional statement if the device matches.

JavaScript
1
2
3
4
5
6
7
8
9
10
<script type="text/javascript">
var iPadAgent = navigator.userAgent.match(/iPad/i) != null;
var iPodAgent = navigator.userAgent.match(/iPhone/i) != null;
var AndroidAgent = navigator.userAgent.match(/Android/i) != null;
var webOSAgent = navigator.userAgent.match(/webOS/i) != null;
if(iPadAgent || iPodAgent || AndroidAgent || webOSAgent){
    alert('This is a mobile device');
}
</script>

It is important to note that there are many additional device names that you should check for if you want full compatibility. Some Android devices are even known to have alternate user agents than just ‘android’. In the future if there is a desire I can compile a full list of all user agents. So post in our feedback tab or comment below!