diff --git a/README.md b/README.md index 208869f..a7f6f07 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1462 TILs and counting..._ +_1463 TILs and counting..._ --- @@ -449,6 +449,7 @@ _1462 TILs and counting..._ - [Check If A Number Is Positive Or Negative](javascript/check-if-a-number-is-positive-or-negative.md) - [Check If File Exists Before Reading It](javascript/check-if-file-exists-before-reading-it.md) - [Check If Something Is An Array](javascript/check-if-something-is-an-array.md) +- [Check Media Queries From JavaScript](javascript/check-media-queries-from-javascript.md) - [Check The Password Confirmation With Yup](javascript/check-the-password-confirmation-with-yup.md) - [Compare The Equality Of Two Date Objects](javascript/compare-the-equality-of-two-date-objects.md) - [Computed Property Names In ES6](javascript/computed-property-names-in-es6.md) diff --git a/javascript/check-media-queries-from-javascript.md b/javascript/check-media-queries-from-javascript.md new file mode 100644 index 0000000..ec43f9a --- /dev/null +++ b/javascript/check-media-queries-from-javascript.md @@ -0,0 +1,28 @@ +# Check Media Queries From JavaScript + +I'm usually thinking about and [using media +queries](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) +from a CSS context. I use them to control what styles are displayed for a +variety of scenarios, such as at different screen widths, when a user prefers +reduced motion, or when the user prefers a dark color scheme. + +The current value of various media queries can be checked from a JavaScript +context as well. + +For instance, if we want to see if the user prefers a _dark_ color schema, we +can look for a _match_ on that media query with +[`matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia). + +```javascript +> window.matchMedia('(prefers-color-scheme: dark)') +MediaQueryList {media: '(prefers-color-scheme: dark)', matches: true, onchange: null} +> window.matchMedia('(prefers-color-scheme: dark)')['matches'] +true +``` + +This queries for the [`prefers-color-scheme` media +feature](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme). + +The [Astro.build Blog +Tutorial](https://docs.astro.build/en/tutorial/6-islands/2/#add-client-side-interactivity) +shows an example of using this to wire up a Light/Dark mode toggle.