Client Side Mobile Device Detection
Device detection can be very complicated. There are entire businesses based on correctly identifying the user's device. Luckily for us to poor to afford such services there is another way to do device detection which doesn't require us to re-invent the wheel.
The actual detection logic comes from Chad Smith and his site: http://detectmobilebrowsers.com. It uses a regular expression to test the user agent string from the device. So far it has correctly detected every mobile device I have thrown at it, but there is a possibility that it may miss a device. Luckily the site is updated frequently, in fact it was just updated six days ago, at the time of writing. I have created an example program which shows one possible way to integrate it into your code. Chad includes code for just about every known web environment, from Apache to Rails, including my favorite, JavaScript.
The site is very simple. It consists of three pages: index.html, desktop.html, and phone.html. Index.html loads and executes the detection script. If it fails, i.e. is not a mobile device, it then jumps to desktop page. If JavaScript is turned off, it simply throws up links to both the desktop and phone pages and allows the user to choose which one they want.
One important thing to note is that only the index page does detection. If the user wants, we allow them to navigate to the desktop page on their phone. This is important, since most desktop sites have more features than their mobile counterparts. If the user isn't able to achieve their goal on the mobile site and you don't allow them to go to the desktop site, they might not come back.
The key part of the detection script, detectmobilebrowser.js, is towards the end. There it needs a link to go if it successfully detects a mobile browser. In my case it is phone.html. The demo code only detects mobile phones, not tablets. There are instructions on how to change the detection code to also detect tablets here.
To try the detection code for yourself, click the link below then select
"Mobile Detect".
"Mobile Detect".
For your own site, I recommend that you download the detection code from Detect Mobile Browsers. No telling when the code may get updated again. Also, if you use the detection code in your business, please consider giving Chad a donation to encourage him to keep it updated.