🚧 DEPRECATED - This repository is deprecated in favor of mqr and will not be updated anymore. Use at your own risk.
Javascript handling for mediaquery breakpoints.
This small library is a wrapper for matchMedia and matchMedia.listen to easily deal with Media Queries in Javascript.
None.
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.
Install it via npm or download the source directly.
npm install responsive-state-manager --saveClassic
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");Initialize it:
var sm = new StateManager();Registers a listener for a Media Query. The callback function is triggered every time the breakpoint is passed and the state changes. Additionally the callback is triggered when the Listener gets registered. 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 on register and every time the state changes
if (matches) {
// Media Query matches
} else {
// Media Query doesn't match
}
});Deregisters an attached listener. Accepts a reference to a listener Object.
sm.deregister(handler);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