Skip to content

Commit 0e160dc

Browse files
committed
theme: respect user browser light/dark preference
1 parent 3d308f4 commit 0e160dc

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

assets/js/_main.js

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,48 @@
33
========================================================================== */
44

55
$(document).ready(function () {
6-
// Set the theme on page load
6+
// detect OS/browser preference
7+
const browserPref = window.matchMedia('(prefers-color-scheme: dark)').matches
8+
? 'dark'
9+
: 'light';
10+
11+
// Set the theme on page load or when explicitly called
712
var setTheme = function (theme) {
8-
const use_theme = theme || localStorage.getItem("theme") || $("html").attr("data-theme");
13+
const use_theme =
14+
theme ||
15+
localStorage.getItem("theme") ||
16+
$("html").attr("data-theme") ||
17+
browserPref;
18+
919
if (use_theme === "dark") {
1020
$("html").attr("data-theme", "dark");
1121
$("#theme-icon").removeClass("fa-sun").addClass("fa-moon");
1222
} else if (use_theme === "light") {
1323
$("html").removeAttr("data-theme");
1424
$("#theme-icon").removeClass("fa-moon").addClass("fa-sun");
1525
}
16-
}
26+
};
27+
1728
setTheme();
1829

19-
// Toggle the theme
30+
// if user hasn't chosen a theme, follow OS changes
31+
window
32+
.matchMedia('(prefers-color-scheme: dark)')
33+
.addEventListener("change", (e) => {
34+
if (!localStorage.getItem("theme")) {
35+
setTheme(e.matches ? "dark" : "light");
36+
}
37+
});
38+
39+
// Toggle the theme manually
2040
var toggleTheme = function () {
2141
const current_theme = $("html").attr("data-theme");
2242
const new_theme = current_theme === "dark" ? "light" : "dark";
2343
localStorage.setItem("theme", new_theme);
2444
setTheme(new_theme);
25-
}
26-
$('#theme-toggle').on('click', function () {
27-
toggleTheme();
28-
});
45+
};
46+
47+
$('#theme-toggle').on('click', toggleTheme);
2948

3049
// These should be the same as the settings in _variables.scss
3150
const scssLarge = 925; // pixels

0 commit comments

Comments
 (0)