Wednesday, November 13, 2013

Differentiating mobiles and tablets in Javascript via User Agent

User agent for Android is pretty confusing - There's no separate UA for Android tablets. Hence, I came up with a generalized UA detection technique to differentiate tablets (Android and iPad) from mobile phone UAs. This will particularly be useful when you'd want to render separate layouts for Mobile and Tablet. Here's the JS code:

function getUserAgent(){
 var ua = navigator.userAgent.toLowerCase();
 if((ua.indexOf("iphone") !== -1) || ((ua.indexOf("mobile") !== -1) && (ua.indexOf("android") !== -1))){
  //The device is a mobile.
 else if((ua.indexOf("ipad") !== -1) || (ua.indexOf("android") !== -1)){
  //The device is a tablet.
  //Desktop or unrecognised device.

You can also take a look at the same code as a Gist on Github and do check out other gists/projects by me.

1 comment:

  1. Thanks your blog is awesome.
    we provide prepaid postpaid service for more detail contact our website
    videocon recharge