6

From a JavaScript program, I would like to be able to tell if Bootstrap considers the current display size to be xs, sm, md, or lg.

This works:

In the HTML write this:

<p class="visible-xs-block xyzzy" data-size="xs"></p>
<p class="visible-sm-block xyzzy" data-size="sm"></p>
<p class="visible-md-block xyzzy" data-size="md"></p>
<p class="visible-lg-block xyzzy" data-size="lg"></p>

Then in JavaScript (with JQuery), this expression

$('.xyzzy:visible').attr('data-size')

returns either xs, sm, md, or lg.

This works, but it seems to me to be a rather clumsy way of doing it.

Is there a simpler way?

oz1cz
  • 5,504
  • 6
  • 38
  • 58
  • 2
    I think you have your answer here: [http://stackoverflow.com/questions/18575582/how-to-detect-responsive-breakpoints-of-twitter-bootstrap-3-using-javascript](http://stackoverflow.com/questions/18575582/how-to-detect-responsive-breakpoints-of-twitter-bootstrap-3-using-javascript) – Kiran Dash Oct 09 '15 at 13:05
  • Possible duplicate of [How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?](http://stackoverflow.com/questions/18575582/how-to-detect-responsive-breakpoints-of-twitter-bootstrap-3-using-javascript) – jabbascript May 19 '17 at 21:20

1 Answers1

3

Using the latest version (Responsive Bootstrap Toolkit 2.5.0):

(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);
Kiran Dash
  • 4,816
  • 12
  • 53
  • 84