Detect System Theme Preference Change Using JavaScript / / No Comments JavaScript and CSS allow users to detect the user theme preference with CSS’ prefers-color-scheme media query. It’s standard these days to use that preference to show the dark or light theme on a given website. But what if the user changes their preference while using your app? To detect a system theme preference change using JavaScript, you need to combine matchMedia, prefers-color-scheme, and an event listener: window.matchMedia('(prefers-color-scheme: dark)') .addEventListener('change',({ matches }) ={ if (matches) { console.log("change to dark mode!") } else { console.log("change to light mode!") } }) The change event of the matchMedia API notifies you... more → Posted in: JavaScript Tagged with: Change, Detect, JavaScript, Preference, system, theme, using
Detect Dark Mode Preference with JavaScript / / No Comments Seemingly every website, dapp, and app offers a dark mode preference, and thank goodness. Dark mode is especially useful when I’m doing late night coding, or even worse, trading into altcoins. I’m presently working on implementing a dark theme on MetaMask and it got me to thinking: is there a way we can default to dark mode if the user’s operating system also defaults to dark mode? You can determine if the user’s operating system prefers dark mode with one quick line of code: const prefersDarkMode = window.matchMedia("(prefers-color-scheme:dark)").matches; // true This code snippet takes advantage of the CSS prefers-color-scheme media query with JavaScript’s... more → Posted in: JavaScript Tagged with: dark, Detect, JavaScript, Mode, Preference