which is the fastest and easy way to fire when bootstrap-responsive.css media queries go in action?
go in action = when you resize window to mobile width and site is
Excellent Tip, @falsarella!
For those who like this sort of thing to not affect their actual markup the following works:
$(function(){
...
var mqClasses = ["visible-xs", "visible-sm", "visible-md", "visible-lg"];
var mq = $("<span id='mqDetector' style='visibility:hidden'></span>").appendTo($("body"));
$.each(mqClasses, function(idx, val) {
mq.append("<span class='" + val + "'></span>");
});
function checkMQ() {
var visible = mq.find(":visible").get(0).className;
return visible.slice(-2);
};
function checkResize(){
switch(checkMQ){
case 'xs' : ...; break;
case 'sm' : ...; break;
...
}
}
$(window).on('resize', checkResize);
checkResize(); //do it once when page loads.
Simpler
$(window).on('resize', function () {
if ($('<div class="visible-lg">').css('display')=='block') {
// Do something for lg
}
// ...
});
I came up with an approach that uses window resize event, but relying on Twitter Bootstrap's media queries without hard coding their breakpoints:
<span id="mq-detector">
<span class="visible-xs"></span>
<span class="visible-sm"></span>
<span class="visible-md"></span>
<span class="visible-lg"></span>
</span>
#mq-detector {
visibility: hidden;
}
var currMqIdx = undefined;
var mqDetector = $("#mq-detector");
var mqSelectors = [
mqDetector.find(".visible-xs"),
mqDetector.find(".visible-sm"),
mqDetector.find(".visible-md"),
mqDetector.find(".visible-lg")
];
var checkForResize = function() {
for (var i = 0; i <= mqSelectors.length; i++) {
if (mqSelectors[i].is(":visible")) {
if (currMqIdx != i) {
currMqIdx = i;
console.log(mqSelectors[i].attr("class"));
}
break;
}
}
};
$(window).on('resize', checkForResize);
checkForResize();
Improving the excellent @falsarella answer, here is a shorter version that works with Bootstrap 4 :
#mq-detector {
visibility: hidden;
}
<div id="mq-detector">
<span data-mq="xs" class="d-block d-sm-none"></span>
<span data-mq="sm" class="d-none d-sm-block d-md-none"></span>
<span data-mq="md" class="d-none d-md-block d-lg-none"></span>
<span data-mq="lg" class="d-none d-lg-block d-xl-none"></span>
<span data-mq="xl" class="d-none d-xl-block"></span>
</div>
//Define function that returns the currently used media query
function getBsMq(){
var currMq;
var mqDetector = $('#mq-detector [data-mq]');
mqDetector.each(function(i){
if ($(this).is(':visible')) {
currMq = $(this).attr('data-mq');
}
});
return currMq;
}
//Call the function and get the currently used media query
alert(getBsMq());