Skip to content

Instantly share code, notes, and snippets.

@liamnewmarch
Created April 23, 2020 16:34
Show Gist options
  • Save liamnewmarch/6f14796ebad4b2d29e6a2983b7293456 to your computer and use it in GitHub Desktop.
Save liamnewmarch/6f14796ebad4b2d29e6a2983b7293456 to your computer and use it in GitHub Desktop.
Get the initial state of a media query and watch for changes with one easy function.
function watchMediaQuery(media, truthy = true, falsy = false) {
const listeners = [];
const mediaQuery = matchMedia(`(${media}: ${truthy})`);
mediaQuery.addListener(() => {
for (const listener of listeners) listener();
});
return (fn) => {
const listener = () => fn(mediaQuery.matches ? truthy : falsy)
listeners.push(listener);
listener();
return () => {
listeners.slice(listeners.findIndex(value => value === listener));
};
};
}
// USAGE
// Create the watcher
const colorScheme = watchMediaQuery('prefers-color-scheme', 'dark', 'light');
// Get initial state and start listening
const remove = colorScheme((value) => {
console.log('Color scheme is', value);
});
// Stop listening
remove();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment