File tree 2 files changed +30
-1
lines changed 2 files changed +30
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1462 TILs and counting..._
13
+ _ 1463 TILs and counting..._
14
14
15
15
---
16
16
@@ -449,6 +449,7 @@ _1462 TILs and counting..._
449
449
- [ Check If A Number Is Positive Or Negative] ( javascript/check-if-a-number-is-positive-or-negative.md )
450
450
- [ Check If File Exists Before Reading It] ( javascript/check-if-file-exists-before-reading-it.md )
451
451
- [ Check If Something Is An Array] ( javascript/check-if-something-is-an-array.md )
452
+ - [ Check Media Queries From JavaScript] ( javascript/check-media-queries-from-javascript.md )
452
453
- [ Check The Password Confirmation With Yup] ( javascript/check-the-password-confirmation-with-yup.md )
453
454
- [ Compare The Equality Of Two Date Objects] ( javascript/compare-the-equality-of-two-date-objects.md )
454
455
- [ Computed Property Names In ES6] ( javascript/computed-property-names-in-es6.md )
Original file line number Diff line number Diff line change
1
+ # Check Media Queries From JavaScript
2
+
3
+ I'm usually thinking about and [ using media
4
+ queries] ( https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries )
5
+ from a CSS context. I use them to control what styles are displayed for a
6
+ variety of scenarios, such as at different screen widths, when a user prefers
7
+ reduced motion, or when the user prefers a dark color scheme.
8
+
9
+ The current value of various media queries can be checked from a JavaScript
10
+ context as well.
11
+
12
+ For instance, if we want to see if the user prefers a _ dark_ color schema, we
13
+ can look for a _ match_ on that media query with
14
+ [ ` matchMedia ` ] ( https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia ) .
15
+
16
+ ``` javascript
17
+ > window .matchMedia (' (prefers-color-scheme: dark)' )
18
+ MediaQueryList {media: ' (prefers-color-scheme: dark)' , matches: true , onchange: null }
19
+ > window .matchMedia (' (prefers-color-scheme: dark)' )[' matches' ]
20
+ true
21
+ ```
22
+
23
+ This queries for the [ ` prefers-color-scheme ` media
24
+ feature] ( https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme ) .
25
+
26
+ The [ Astro.build Blog
27
+ Tutorial] ( https://docs.astro.build/en/tutorial/6-islands/2/#add-client-side-interactivity )
28
+ shows an example of using this to wire up a Light/Dark mode toggle.
You can’t perform that action at this time.
0 commit comments