snippetjavascriptTip
Detect user color scheme preference in JavaScript
Viewed 0 times
javascriptuserdetectcolorschemepreference
Problem
The recently introduced
Combining the media query with the
The same technique can be used for checking if the user prefers a light color scheme. Bear in mind, however, that
prefers-color-scheme media query allows us to check if the user prefers a light or dark color scheme. This can be a useful tool when implementing a dark mode for your website or web application.Combining the media query with the
Window.matchMedia() method allows us to check if the user has selected a dark color scheme ('dark') in their operating system settings.The same technique can be used for checking if the user prefers a light color scheme. Bear in mind, however, that
'light' is the default value for the prefers-color-scheme media query. This means that it might also mean that the user has not expressed a preference.Solution
const prefersDarkColorScheme = () =>
window &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;The same technique can be used for checking if the user prefers a light color scheme. Bear in mind, however, that
'light' is the default value for the prefers-color-scheme media query. This means that it might also mean that the user has not expressed a preference.Code Snippets
const prefersDarkColorScheme = () =>
window &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;const prefersLightColorScheme = () =>
window &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: light)').matches;Context
From 30-seconds-of-code: prefers-color-scheme
Revisions (0)
No revisions yet.