Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Bootstrap's display size from JavaScript

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?

like image 778
oz1cz Avatar asked Oct 31 '22 17:10

oz1cz


1 Answers

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);
like image 103
Kiran Dash Avatar answered Nov 11 '22 04:11

Kiran Dash