Chris 2pha Brown. Drupal developer Brisbane Australia

Chris Brown

Drupal, Javascript, Three.js, 3D

website blog
image for Drupal Bootstrap 3 theme media queries javascript event (like Omega 3)

Drupal Bootstrap 3 theme media queries javascript event (like Omega 3)

Having used the Omega 3 Drupal theme for a few years now I got quite use to writing javascript functions that would react to the 'reponsivelayout' event that was supplied by the theme. This event would fire after the responsive classes were applied to the body tag when the page loaded or when the media queries changed the site layout.
I often used this event to create things like mobile menus and such.
Now on the latest site I am building I am trying out the Bootstrap theme which does not fire such an event, so I thought I would add one that basically uses javascript similar to the Omega 3 theme.
If you would like the same, just add a js file to your Bootstrap sub theme with the js below:

(function($) {

  var setCurrentLayout = function (oldLayout, newLayout) {
    $('body').removeClass('responsive-layout-'+oldLayout).addClass('responsive-layout-'+newLayout);
    $.event.trigger('responsivelayout', {from: oldLayout, to: newLayout});
  };

  var checkCurrentLayout = function () {
    var current = 'xs';
    var dummy = $('<div id="bootstrap-media-query-dummy" class="container"></div>').prependTo('body');
    var width = dummy.outerWidth();

    if (width > 750 - 1) {
      current = 'sm';
    }
    if (width > 970 - 1) {
      current = 'md';
    }
    if (width > 1170 - 1) {
      current = 'lg';
    }
    dummy.remove();
    if (typeof Drupal.settings.currentLayout == 'undefined') {
      Drupal.settings.currentLayout = current;
      setCurrentLayout('', current);
    } else if (Drupal.settings.currentLayout != current) {
      var old = Drupal.settings.currentLayout;
      Drupal.settings.currentLayout = current;
      setCurrentLayout(old, current);
    }
  }

  Drupal.behaviors.bootstrapMediaQueries = {
    attach: function (context) {
      $('body', context).once('bootstrap-mediaqueries', function () {
        $(window).bind('resize.bootstrapmediaqueries', function () {
          checkCurrentLayout();
        }).load(function () {
          $(this).trigger('resize.bootstrapmediaqueries');
        });
      });
    }
  };

})(jQuery);

Now, to react to the event, just listen for the 'reponsivelayout' event, same as in Omega 3:

  Drupal.behaviors.myfunction = {
    attach:function(context, settings){
      $(document, context).on('responsivelayout', function(e, data) {
        console.log(data.from);
        console.log(data.to);
      });
    }
  };

Add a comment

<b>, <i> and <code> tags are allowed.