How to Detect and Run JavaScript When Bootstrap Media Query Breakpoints Change

Download FREE Marketing Guides
How to Detect and Run JavaScript When Bootstrap Media Query Breakpoints Change

Update: I created a small jQuery plugin that adds media query detection for Bootstrap 3 and 4 projects. You can learn more about IfBreakpoint.js here.

Have you ever wanted to trigger some javascript at a certain media query value? Relying on document.width() has problems because it includes browser scrollbars. A simpler and more accurate solution is to rely on CSS to trigger the javascript.

Bootstrap 3 has some nice responsive visibility classes that are triggered at the various breakpoints. What we will do is add a series of span tags with these classes and check when they are set to display block. Since they are inline by default, we will know media query breakpoint fired when the CSS display property changes.

View Demo

Adds some invisible span elements to trigger Bootstrap CSS media queries

$( "body" ).append( "" );

Write a function to check if an element is set to display block

// Checks if the span is set to display block via CSS
function checkIfBlock (target) {
    var target = $(target).css('display') == 'block';
    return target;
}

Set some variables to use with the if conditional statements below

// Set some variables to use with the if checks below
var mediaQueryXs = checkIfBlock('.viewport-check .visible-xs-block');
var mediaQuerySm = checkIfBlock('.viewport-check .visible-sm-block');
var mediaQueryMd = checkIfBlock('.viewport-check .visible-md-block');
var mediaQueryLg = checkIfBlock('.viewport-check .visible-lg-block');

Now write a series of if condition statements to check if they are true/false

// Now check if the media query is enabled then add a unique class to the body tag
// Are you extra-small?
if ( mediaQueryXs == true ) {
        $("body").toggleClass( "media-query-xs" );
  $("h2").text( "media-query-xs" );
}

// Are you small?
if ( mediaQuerySm == true ) {
        $("body").toggleClass( "media-query-sm" );
   $("h2").text( "media-query-sm" );
}

// Are you medium?
if ( mediaQueryMd == true ) {
        $("body").toggleClass( "media-query-md" );
   $("h2").text( "media-query-md" );
}

// Are you large?
if ( mediaQueryLg == true ) {
        $("body").toggleClass( "media-query-lg" );
   $("h2").text( "media-query-lg" );
} 

Below is the completed script

Works cited
http://stackoverflow.com/questions/20181219/twitter-bootstrap-how-to-detect-when-media-queries-starts
http://jsfiddle.net/ejVvu/1/


Written by: Jake Lett
I share digital marketing tips and HubSpot tutorials to help marketers and business owners grow their business.

Related posts

Tags:

Want to Get Email Updates of New Articles?

Join My Email Newsletter