Media Check

Control JavaScript based on media query definitions

mediaCheck is a simple wrapper around matchMedia to run code on entry and exit from media queries. Version 1 drops support for browsers without matchMedia support. If you need to support older browsers, you can use an older version.

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');
    }
  });

  import mediaCheck from './mediaCheck';

  const demo = document.querySelector('.demo-area');

  function smallScreen(mq) {
    if (mq.media)
    demo.innerText = 'This is a smaller screen.';
    demo.classList.add('green');
    demo.classList.remove('blue', 'orange');
  }

  function largeScreen(mq) {
    debugger;
    if (document.body.offsetWidth >= 900) {
      // Note: Because this gets called by both mediaquery checks,
      // it needs to make sure that it actually needs to apply so
      // it doesn't overwrite the smallScreen message.

      demo.innerText = 'This is a larger screen.';
      demo.classList.add('orange');
      demo.classList.remove('blue', 'green');
      console.log(demo.classList);
    }
  }

  function dude(mq) {
    demo.innerText = "Dude, that's a really big screen.";
    demo.classList.add('blue');
    demo.classList.remove('orange', 'green');
  }

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

  mediaCheck({
    media: '(min-width: 1200px)',
    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.