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]).