How to detect device type with JavaScript?

There is a simple way how to detect if user is accessing your web site using mobile device (like phone, tablet or their hybrid brother phablet) or stationary device. You can detect it using navigator object. We will neglect small players on the mobile market and focus only on the main players. Example:

var mobile = {
  Android: function() {
    return navigator.userAgent.match(/Android/i);
  },
  BlackBerry: function() {
    return navigator.userAgent.match(/BlackBerry/i);
  },
  iOS: function() {
    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
  },
  Opera: function() {
    return navigator.userAgent.match(/Opera Mini/i);
  },
  Windows: function() {
    return navigator.userAgent.match(/IEMobile/i);
  },
  any: function() {
    return (mobile.Android() || mobile.BlackBerry() || mobile.iOS() || mobile.Opera() || mobile.Windows());
  }
};

If you are interested if user is accessing your site using BlackBerry (obscure example, I know – why would anyone care about BlackBerry 🙂 ) you can do it like this:

var isandroid = function() {
  mobileArray = mobile.BlackBerry();
  if(typeof mobileArray !== 'undefined' && mobileArray != null && mobileArray.length > 0) {
    return true;
  }
  return false;
}

Or shortly:

var isandroid = function() {
  mobileArray = mobile.BlackBerry();
  return (typeof mobileArray !== 'undefined' && mobileArray != null && mobileArray.length > 0);
}

Leave a Comment.