Created
April 23, 2020 16:34
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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