Media events is a tiny library that makes javascript media queries easy; allowing you to write @media rules just as you would with CSS.
npm install media-events --save
or
bower media-events
// Construct a media object like this
const media = new MediaEvent({
landscape: '(orientation: landscape)',
small: '(max-width: 600px)',
});
// Now the state can be inspected
if (media.state.small) handleSmall();
else if (!media.state.landscape) handlePortrait();
else handleEveryElse();
// Updates events are emitted every time something changes
media.on('update', (state) => handleUpdate(state));
// The media object just extends EventEmitter, so all the normal methods work
media.once('update', (state) => handleOneUpdate(state));
media.removeListener('update', handleUpdate);
// This is great for React.js components
media.on('update', (state) => this.setState({ mediaState: state }));
// Or for Flux/Redux/{Whatever}ux
media.on('update', (state) => store.dispatch({ type: 'MEDIA_UPDATE', mediaState: state }));
// Events are also emitted for when individual sub-queries match
media.on('small', () => smallNow());
media.on('landscape', () => landscapeNow());
// And just for symmetry
media.on('not-small', () => notSmallNow());
// Clean up
media.destroy();
coming soon...
Just EventEmitter
from Node.js and the Window.matchMedia and
MediaQueryListListener APIs.
See the MDN compatibility table for Window.matchMedia: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia#Browser_compatibility