|
3 | 3 | ========================================================================== */
|
4 | 4 |
|
5 | 5 | $(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 |
7 | 12 | 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 | + |
9 | 19 | if (use_theme === "dark") {
|
10 | 20 | $("html").attr("data-theme", "dark");
|
11 | 21 | $("#theme-icon").removeClass("fa-sun").addClass("fa-moon");
|
12 | 22 | } else if (use_theme === "light") {
|
13 | 23 | $("html").removeAttr("data-theme");
|
14 | 24 | $("#theme-icon").removeClass("fa-moon").addClass("fa-sun");
|
15 | 25 | }
|
16 |
| - } |
| 26 | + }; |
| 27 | + |
17 | 28 | setTheme();
|
18 | 29 |
|
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 |
20 | 40 | var toggleTheme = function () {
|
21 | 41 | const current_theme = $("html").attr("data-theme");
|
22 | 42 | const new_theme = current_theme === "dark" ? "light" : "dark";
|
23 | 43 | localStorage.setItem("theme", new_theme);
|
24 | 44 | setTheme(new_theme);
|
25 |
| - } |
26 |
| - $('#theme-toggle').on('click', function () { |
27 |
| - toggleTheme(); |
28 |
| - }); |
| 45 | + }; |
| 46 | + |
| 47 | + $('#theme-toggle').on('click', toggleTheme); |
29 | 48 |
|
30 | 49 | // These should be the same as the settings in _variables.scss
|
31 | 50 | const scssLarge = 925; // pixels
|
|
0 commit comments