Skip to content
This repository was archived by the owner on Jun 25, 2020. It is now read-only.

benjaminjt/media-events

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

29 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Media Events Logo

Travis License

Media events is a tiny library that makes javascript media queries easy; allowing you to write @media rules just as you would with CSS.

Installation

npm install media-events --save

or

bower media-events

Quick Start

// 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();

Full Examples

coming soon...

Dependencies

Just EventEmitter from Node.js and the Window.matchMedia and MediaQueryListListener APIs.

Compatability

See the MDN compatibility table for Window.matchMedia: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia#Browser_compatibility

About

A lightweight wrapper for Window.matchMedia() with events

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published