Menu icon Foundation
Media Query based JS

What would be the best way to introduce JS to fire at different breakpoints based on what small/medium/large are set to in SCSS?

Is there an official way or is it best to write some modernizer mq tests as: http://modernizr.com/docs/#mq

modernizrjsmedia query

What would be the best way to introduce JS to fire at different breakpoints based on what small/medium/large are set to in SCSS?

Is there an official way or is it best to write some modernizer mq tests as: http://modernizr.com/docs/#mq

Nic Mendoza over 5 years ago

This has been sitting here for a while, but since I was looking to do something along these lines, how about something like the following. It allows you to subscribe to resize events like so, which will fire at most every 250 milliseconds when the window is resized:

 $('body').on('resize.fndtn.media', function(event,size){
   // do something with size, which will be one of the sizes 
   // "small", "medium", etc.
});

It does bring in underscore as a depency for throttling, but you could easily remove that (threw it in a UMD wrapper for use with AMD-style loaders or as a drop-in)

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['modernizr','app','jquery', 'underscore'], factory);
    } else {
        // Browser globals
       factory(root.Modernizr,root.Foundation,root.$, root._);
    }
}(this, function (Modernizr,Foundation,$,_){

  var sizes = ['small','medium','large','xlarge','xxlarge'],
    mediaQueries = sizes.map(function(size){
      return {
        size: size,
        query: Foundation.media_queries[size]
      };
    }),
    cachedSize;

  $(window).on( 'resize', _.throttle(checkQueriesAndPublishFactory(), 100 ) );

  function checkQueriesAndPublishFactory(){
    return function(){
      checkAndpublish(checkQueries());
    }
  }

  function checkQueries(){

    var size;

    mediaQueries.every(function(mediaQuery){
      if(Modernizr.mq(mediaQuery.query)){
        size = mediaQuery.size;
        return true;
      } else {
        return false;
      }
    });

    return size;
  }

  function checkAndpublish(size){
    if(size !== cachedSize ){
      $('body').trigger('resize.fndtn.media',size);
      cachedSize = size;
    }

  }

}));