How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

Edit: This library is now available through Bower and NPM. See github repo for details.

UPDATED ANSWER:

Disclaimer: I’m the author.

Here’s a few things you can do using the latest version (Responsive Bootstrap Toolkit 2.5.0):

// Wrap everything in an IIFE
(function($, viewport){

    // Executes only in XS breakpoint
    if( viewport.is('xs') ) {
        // ...
    }

    // Executes in SM, MD and LG breakpoints
    if( viewport.is('>=sm') ) {
        // ...
    }

    // Executes in XS and SM breakpoints
    if( viewport.is('<md') ) {
        // ...
    }

    // Execute only after document has fully loaded
    $(document).ready(function() {
        if( viewport.is('xs') ) {
            // ...
        }
    });

    // Execute code each time window size changes
    $(window).resize(
        viewport.changed(function() {
            if( viewport.is('xs') ) {
                // ...
            }
        })
    ); 

})(jQuery, ResponsiveBootstrapToolkit);

As of version 2.3.0, you don’t need the four <div> elements mentioned below.


ORIGINAL ANSWER:

I don’t think you need any huge script or library for that. It’s a fairly simple task.

Insert the following elements just before </body>:

<div class="device-xs visible-xs"></div>
<div class="device-sm visible-sm"></div>
<div class="device-md visible-md"></div>
<div class="device-lg visible-lg"></div>

These 4 divs allow you check for currently active breakpoint. For an easy JS detection, use the following function:

function isBreakpoint( alias ) {
    return $('.device-' + alias).is(':visible');
}

Now to perform a certain action only on the smallest breakpoint you could use:

if( isBreakpoint('xs') ) {
    $('.someClass').css('property', 'value');
}

Detecting changes after DOM ready is also fairly simple. All you need is a lightweight window resize listener like this one:

var waitForFinalEvent = function () {
      var b = {};
      return function (c, d, a) {
        a || (a = "I am a banana!");
        b[a] && clearTimeout(b[a]);
        b[a] = setTimeout(c, d)
      }
    }();

var fullDateString = new Date();

Once you’re equipped with it, you can start listening for changes and execute breakpoint-specific functions like so:

$(window).resize(function () {
    waitForFinalEvent(function(){

        if( isBreakpoint('xs') ) {
            $('.someClass').css('property', 'value');
        }

    }, 300, fullDateString.getTime())
});

Leave a Comment