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);

How to detect user’s device size (xs, sm, md or lg) using Bootstrap?

Today I am going to show you a simple “hack” – how to detect device size using Bootstrap (and a short snippet of jQuery). In order to make it work you obviously have to import Bootstrap and jQuery JS and CSS files.

Firstly you create a div with four containing divs:

<div id="users-device-size">
  <div id="xs" class="visible-xs"></div>
  <div id="sm" class="visible-sm"></div>
  <div id="md" class="visible-md"></div>
  <div id="lg" class="visible-lg"></div>

Those divs will of course never show on your site. Their sole purpose is to tell you the device size. After that you have to add short function to your JS file (or to your JavaScript section inside of your HTML):

function getBootstrapDeviceSize() {
  return $('#users-device-size').find('div:visible').first().attr('id');

This function will retrieve current visible div’s id, which tells you the device size in Bootstrap way (xs – extra small device [<768px], sm – small device [>=768px], md – medium device [>=992px] and lg – large device [>=1200px]).