Skip to content

Commit d1baf76

Browse files
committed
Add match-media til
1 parent 6e37fc2 commit d1baf76

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

javascript/match-media.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
date: 2024-07-10
3+
---
4+
5+
# Use media queries in javascript with the `matchMedia()` method
6+
7+
Today I learned that the `matchMedia()` javascript method lets you match against media queries and respond accordingly with javascript.
8+
9+
That could look something like this:
10+
11+
```js
12+
const mediaQuery = window.matchMedia('(min-width: 768px)')
13+
// Check if the media query is true
14+
if (mediaQuery.matches) {
15+
// Then trigger an alert
16+
alert('Media Query Matched!')
17+
}
18+
```
19+
You can also add an event listener to the `mediaQuery` which you'll want to do to respond to the user changing the size of the window — see [this post](https://css-tricks.com/working-with-javascript-media-queries/) for details on how to do that.
20+
21+
Ideally, I try to keep media queries in CSS but this can come in handy for example if you want to change the way a tooltip behaves on smaller screens.
22+

0 commit comments

Comments
 (0)