CSS Media query in JS
Installation
npm install js-media-query
Usage
import Media from "js-media-query";
import { up, sm, md } from "js-media-query";
See Examples
API
Method | Description |
---|
query | Check media query matching |
min | Minimum breakpoint width |
max | Maximum breakpoint width |
up | Minimum breakpoint width |
down | Maximum breakpoint width |
between | Check if screen between the from and to breakpoints |
isTouch | Check if is touck device |
isMouse | Check if is non-touch device |
xs | Check if screen is bigger or equal to xs class defined breapoint |
sm | Check if screen is bigger or equal to sm class defined breapoint |
md | Check if screen is bigger or equal to md class defined breapoint |
lg | Check if screen is bigger or equal to lg class defined breapoint |
xl | Check if screen is bigger or equal to xl class defined breapoint |
setBreakpoints | Set Local class breapoints |
Events
on(event, callback, media)
Prop | Value | Required | Description |
---|
event | in , out , changed | yes | Event type |
callback | function | yes | Callback function reference |
media | function | yes | Function reference what return result of required media query |
off(event, callback?, media?)
Prop | Value | Required | Description |
---|
event | in , out , changed | yes | Event type |
callback | function | yes | Callback function reference |
media | function | yes | Function reference what return result of required media query |
Examples
Basic Usage
import { min } from "js-media-query";
window.addEventListener("resize", () => {
if (min(992)) {
console.log("Screen size is equals or bigger than 992px");
} else {
console.log("Screen size is lower than 992px");
}
});
Using with default breakpoints
import Media from "js-media-query";
if (Media.sm()) {
}
Using with custom breakpoints
import { Media } from "js-media-query";
const media = new Media({
xs: 0,
sm: 576,
md: 768,
lg: 992,
xl: 1200,
});
if (media.md()) {
}
Event listening
import { Media } from "js-media-query";
const media = new Media();
const changedHandler = () => {
console.log("changed");
};
const mediaFn = () => media.up(768);
media.on("changed", changedHandler, mediaFn);
media.off("changed");
media.off("changed", changedHandler);
media.off("changed", changedHandler, mediaFn);
@media (min-width: 768px) AND (max-width: 992px)
Media.between(768, 992);
@media (pointer: coarse)
Media.isTouch();
@media (min-width: 992px)
Media.min(992);
@media (max-width: 991px)
Media.down(991);
@media (min-width: 1200px)
Media.xl();