CSS Media queries are great, and thanks to matchMedia
we can use them in JavaScript just as easily.
This is a handy function for attaching listening to a media query, and a cleanup function.
function mediaQuery(query, handler) {
const media = window.matchMedia(query);
const listener = () => {
if (media.matches) {
handler();
}
};
media.addListener(listener);
return () => media.removeListener(listener);
}
Detecting screen size:
const unsubscribe = mediaQuery('(max-width: 768px)', () => {
console.log('window is less than 768px'):
});
unsubscribe();
Detecting dark mode preference:
const unsubscribe = mediaQuery('(prefers-color-scheme: dark)', () => {
console.log('use dark mode'):
});
unsubscribe();