StateManager
Javascript handling for mediaquery breakpoints.
This small library is a wrapper for matchMedia
and matchMedia.listen
to easily deal with Media Queries in Javascript.
Dependencies
None.
Supported Browsers
StateManager relies on window.matchMedia
for Media Query checks which is supported by the following browsers:
- Chrome 10+
- Firefox 6+
- Safari 5.1+
- IE 10+
To support legacy browsers a polyfill is required.
Installation
Install it via npm or download the source directly.
npm install responsive-state-manager --save
Classic
Include StateManager.min.js
before the closing body
tag.
<script src="node_modules/responsive-state-manager/dist/StateManager.min.js"></script>
CommonJS
var StateManager = require("responsive-state-manager");
Usage
Initialize it:
var sm = new StateManager();
.register()
Registers a listener for a Media Query. The callback function is triggered every time the breakpoint is passed and the state changes. The suplied argument is true
or false
depending on whether the Media Query matches.
It returns a reference to the Listener Object.
var handler = sm.register("screen and (max-width: 768px)", function (matches) {
// fires every time the state changes
console.log(matches); // true if query matches
});
.deregister()
Deregisters an attached listener. Accepts a reference to a listener Object.
sm.deregister(handler);
.matches()
You can also check directly if a media query matches.
var mobile = sm.matches("screen and (max-width: 768px)"); // does not attach listener
console.log(mobile); // true/false