Skip to content

Commit 8f2f92b

Browse files
committed
Add matchMedia for dark mode
1 parent f184322 commit 8f2f92b

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8735,6 +8735,31 @@ The execution context is created when a function is called. The function's code
87358735
87368736
**[⬆ Back to Top](#table-of-contents)**
87378737
8738+
464. ### How to detect system dark mode in javascript?
8739+
8740+
The combination of `Window.matchMedia()` utility method along with media query is used to check if the user has selected a dark color scheme in their operating system settings or not. The CSS media query `prefers-color-scheme` needs to be passed to identify system color theme.
8741+
8742+
The following javascript code describes the usage,
8743+
8744+
```javascript
8745+
const hasDarkColorScheme = () =>
8746+
window.matchMedia &&
8747+
window.matchMedia('(prefers-color-scheme: dark)').matches;
8748+
```
8749+
8750+
You can also watch changes to system color scheme using `addEventListener`,
8751+
8752+
```javascript
8753+
window
8754+
.matchMedia("(prefers-color-scheme: dark)")
8755+
.addEventListener("change", (event) => {
8756+
const theme = event.matches ? "dark" : "light";
8757+
});
8758+
```
8759+
**Note:** The matchMedia method returns **MediaQueryList** object stores information from a media query.
8760+
8761+
**[⬆ Back to Top](#table-of-contents)**
8762+
87388763
<!-- QUESTIONS_END -->
87398764
87408765
### Coding Exercise

0 commit comments

Comments
 (0)