This is a simple technique you can use to test the current viewport size in jQuery leveraging Bootstrap's responsive utilities.

Add the following elements to your global template, just before the closing </body> tag

    <div class="visible-md visible-lg" id="large-desktop-only-visible"></div>
    <div class="visible-sm visible-md visible-lg" id="desktop-only-visible"></div>
    <div class="visible-xs" id="mobile-only-visible"></div>

Then you can use this simple JavaScript logic to call methods depending on the viewport size. Here's an example that will only run on mobile:

(function ($) {
    if ($('#mobile-only-visible').is(':visible'))
        // ... some logic you only need on mobile

You can see how this can be customized to suit your own use cases.

This very simple technique allows for custom code that runs only in certain viewport sizes, and doesn't need any javascript listeners like some other techniques.

Based on a discussion over at Stack Overflow

Last Updated December 16th, 2016