Twitter Bootstrap - how to detect when media queries starts Twitter Bootstrap - how to detect when media queries starts jquery jquery

Twitter Bootstrap - how to detect when media queries starts


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


One issue with the other answers is the change event is triggered EVERY resize. This can be very costly if your javascript is doing something significant.

The code below calls your update function only one time, when a threshold is crossed.

To test, grab your window size handle, and drag resize it quickly to see if the browser chokes.

<script>// Global state variablevar winSize = '';window.onresize = function () {    var newWinSize = 'xs'; // default value, check for actual size    if ($(this).width() >= 1200) {        newWinSize = 'lg';    } else if ($(this).width() >= 992) {        newWinSize = 'md';    } else if ($(this).width() >= 768) {        newWinSize = 'sm';    }    if( newWinSize != winSize ) {        doSomethingOnSizeChange();        winSize = newWinSize;    }};</script>


Using jquery you can find the size of current window and then accordingly do your stuff.

$(window).resize(function() {  if ($(this).width() >= 1280) {    //do something  }  else if ($(this).width() < 1280 && $(this).width()>= 980) {    //do something  }  ...});

CSS:: Twitter-Bootsrap-layouts

/* Large desktop */@media (min-width: 1200px) { ... }/* Portrait tablet to landscape and desktop */@media (min-width: 768px) and (max-width: 979px) { ... }/* Landscape phone to portrait tablet */@media (max-width: 767px) { ... }/* Landscape phones and down */@media (max-width: 480px) { ... }