Sometimes you need to know what type of device your site visitors are using, in order to create a better user experience. You may want to detect mobile devices and redirect them to a mobile optimized version of your site, or simply use different stylesheets or scripts. There are many ways of doing this - feature detection, screen size detection etc. But if you just want to implement a simple JavaScript based check, you could just detect the browser's userAgent
string and take appropriate action.
if ((navigator.userAgent).indexOf("Mobile")) alert("Mobile Device");
The above method just checks if the userAgent string contains the word "Mobile". However only few of the popular mobile browsers have this string in their userAgent string. To include a wider range of devices, you could use Javascript regular expressions, a.k.a. regex. The following code checks if the userAgent string contains any one of the words "Android", "webOS", "iPhone","iPad","BlackBerry","Windows Phone", "Opera Mini", "IEMobile" or "Mobile".
The /expression/i
makes the search case insensitive.
if (/Android|webOS|iPhone|iPad|BlackBerry|Windows Phone|Opera Mini|IEMobile|Mobile/i.test(navigator.userAgent)) alert("Mobile Device");
This code covers many of the popular mobile devices on market, but not all of the minor players. Also the userAgent strings are constantly subject to change as new versions come up and we can only hope the userAgent strings still have these words.
Code
<div id="device" style="text-align: center; border:1px dotted black; color:green;"></div> <script type="text/javascript"> testExp = new RegExp('Android|webOS|iPhone|iPad|' + 'BlackBerry|Windows Phone|' + 'Opera Mini|IEMobile|Mobile' , 'i'); if (testExp.test(navigator.userAgent)) document.getElementById("device").innerHTML = "Your device is a Mobile Device"; else document.getElementById("device").innerHTML = "Your device is NOT a Mobile Device"; </script>