Get Bootstrap Responsive Breakpoint on window resize

Detect Bootstrap responsive grid breakpoints from CSS using JavaScript

by MartinDubeNet

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div class="container">
    <header class="page-header">
        <div class="jumbotron">
            <h1>Bootstrap Grid 4 Flag</h1>
            <p>Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.</p>
        </div>
        <p>This is some text.</p>
        <p>This is another text.</p>
    </header>
</div>

SCSS

body:before {
  /* optional red flag layout */
  position: fixed;
  z-index: 999;
  top: 15px;
  left: 15px;
  color: white;
  padding: 10px 20px;
  opacity: .6;
  border: 2px solid white;
  border-radius: 5px;  
  box-shadow: 2px 2px 10px 3px #333;
  background-color: red;
  /* end of optional red flag layout */

  /* display: none; /* comment this while developping. Switch back to display:NONE when you're done */

  content: 'XS.≤749px'; /* default = mobile first */

  @media screen and (min-width: 576px) {
    content: 'SM.≥576px';
    background-color: blue;
  }
  @media screen and (min-width: 768px) {
    content: 'MD.≥768px';
    background-color: purple;
  }
  @media screen and (min-width: 992px) {
    content: 'LG.≥992px';
    background-color: green;
  }
  @media screen and (min-width: 1200px) {
    content: 'XL.≥1200px';
    background-color: brown;
  }
}

JavaScript

$(document).ready(function () {

    // get bootstrap grid breakpoint from css, repeat everytime window is resized
    getResponsiveBreakpoint();
    $(window).on('resize', function (e) {
        clearTimeout(windowResizeTimer);
        windowResizeTimer = setTimeout(function () {

            getResponsiveBreakpoint();
            console.log('Resized breakpoint name = ' + myBootstrapGrid_name);

        }, 500);
    });
})


/*
* Get Responsive Breakpoint
* get bootstrap grid breakpoint name from css: body:before{content}
*/
var myBootstrapGrid_name =  'xs', // bootstrap default = mobile first
    windowResizeTimer =     '';

function getResponsiveBreakpoint() {
    // get the value from DOM
    myBootstrapGrid_name = window.getComputedStyle(document.querySelector('body'), ':before').getPropertyValue('content').replace(/['"]+/g, '');
    // print the value as class on <html> tag
    document.documentElement.className = document.documentElement.className.replace(/xs|sm|md|lg|xl/gi, myBootstrapGrid_name);
};