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> </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]).
Only javascript way of doing the same… found on stackoverflow.com
function findBootstrapEnvironment() {
var envs = [‘xs’, ‘sm’, ‘md’, ‘lg’];
var $el = $(”);
$el.appendTo($(‘body’));
for (var i = envs.length – 1; i >= 0; i–) {
var env = envs[i];
$el.addClass(‘hidden-‘+env);
if ($el.is(‘:hidden’)) {
$el.remove();
return env;
}
}
}
http://stackoverflow.com/questions/14441456/how-to-detect-which-device-view-youre-on-using-twitter-bootstrap-api
Sharing is caring! Tnx, I appreciate it.
This is awesome!
tnx
Excellent Idea.
many thanks for sharing this code
You are very welcome. 🙂 I wish you all the best.