Skip to content

Commit ab9d2b5

Browse files
committed
Add Check Media Queries From JavaScript as a JavaScript TIL
1 parent aa00c55 commit ab9d2b5

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1462 TILs and counting..._
13+
_1463 TILs and counting..._
1414

1515
---
1616

@@ -449,6 +449,7 @@ _1462 TILs and counting..._
449449
- [Check If A Number Is Positive Or Negative](javascript/check-if-a-number-is-positive-or-negative.md)
450450
- [Check If File Exists Before Reading It](javascript/check-if-file-exists-before-reading-it.md)
451451
- [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)
452453
- [Check The Password Confirmation With Yup](javascript/check-the-password-confirmation-with-yup.md)
453454
- [Compare The Equality Of Two Date Objects](javascript/compare-the-equality-of-two-date-objects.md)
454455
- [Computed Property Names In ES6](javascript/computed-property-names-in-es6.md)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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.

0 commit comments

Comments
 (0)