Skip to content

Commit

Permalink
Implement media-matching to auto-detect client dark mode setting
Browse files Browse the repository at this point in the history
Originally done as part of
perlang-org/perlang@3178955.
I'm not fully convinced whether this is a good idea or not, or whether
it will just make people confused. Nonetheless, this keeps us in track
with the version we have deployed at https://perlang.org
  • Loading branch information
Per Lundberg committed Apr 1, 2021
1 parent e475395 commit 5bd8d97
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion darkerfx/styles/toggle-theme.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
const sw = document.getElementById("switch-style"), b = document.body;

if (sw && b) {
sw.checked = window.localStorage && localStorage.getItem("theme") === "theme-dark" || !window.localStorage;
if (window.localStorage && localStorage.getItem("theme") === "theme-dark") {
// Browser supports local storage and dark mode is configured.
sw.checked = true;
}
else {
// Browser does not support local storage, or no stored theme setting is
// present. Determine dark mode based on browser settings. Browsers
// which don't support media matching will default to light theme, in
// line with what most people would expect from a web page.
sw.checked = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
}

b.classList.toggle("theme-dark", sw.checked)
b.classList.toggle("theme-light", !sw.checked)
Expand Down

0 comments on commit 5bd8d97

Please sign in to comment.