mediaCheck

allows you to control your JavaScript based on your media query definitions

mediaCheck is a simple wrapper around matchMedia to run code on entry and exit from media queries. It also uses browser resize as a fallback for browsers that don't support matchMedia.

Demo

Examples


  mediaCheck({
    media: '(max-width: 420px)',
    entry: function() {
      console.log('starting 420');
    },
    exit: function() {
      console.log('leaving 420');
    },
    both: function() {
      console.log('changing state');
    }
  });


  var $demo = $('.demo-area');

  function smallScreen(mq) {
    if (mq.media)
    $demo.text('This is a smaller screen.');
    $demo.animate({
      backgroundColor: '#19ae2b'
    });
  }

  function largeScreen(mq) {
    if ($(document).width() >= 900) {
      // Note: Because this gets called by both media query checks,
      // it needs to make sure that it actually needs to apply so
      // it doesn't overwrite the smallScreen message.
      $demo.text('This is a larger screen.');
      $demo.animate({
        backgroundColor: '#d3811e'
      });
    }
  }

  function dude(mq) {
    $demo.text("Dude, that's a really big screen.");
    $demo.animate({
      backgroundColor: '#6814d3'
    });
  }

  mediaCheck({
    media: '(min-width: 900px)',
    entry: largeScreen,
    exit: smallScreen
  });

  mediaCheck({
    media: '(min-width: 1400px)',
    entry: dude,
    exit: largeScreen
  });

Options

media

Type: string

This is the mediaquery that will trigger the specified action. It should be in the form:

  • (min-width: 420px)
  • (min-width: 35em)
  • (max-width: 800px)
  • (max-width: 60em)

entry

Type: function

Params: mq The media query object

This function will execute once when the mediaquery becomes active.

exit

Type: function

Params: mq The media query object

This function will execute once when the mediaquery becomes inactive.

both

Type: function

Params: mq The media query object

This function will execute once when the mediaquery changes state.