This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
// Light/dark switch. The page follows the OS theme until the button is used;
|
||||
// the choice is then remembered in localStorage. Loaded in <head> so a saved
|
||||
// theme is applied before the page paints.
|
||||
(function () {
|
||||
var root = document.documentElement;
|
||||
var media = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
|
||||
try {
|
||||
var saved = localStorage.getItem('theme');
|
||||
if (saved === 'light' || saved === 'dark') root.dataset.theme = saved;
|
||||
} catch (e) {}
|
||||
|
||||
function current() {
|
||||
return root.dataset.theme || (media.matches ? 'dark' : 'light');
|
||||
}
|
||||
|
||||
function label(btn) {
|
||||
var next = current() === 'dark' ? 'light' : 'dark';
|
||||
btn.textContent = next === 'dark' ? 'Dark mode' : 'Light mode';
|
||||
btn.setAttribute('aria-label', 'Switch to ' + next + ' mode');
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
var btn = document.getElementById('theme-toggle');
|
||||
if (!btn) return;
|
||||
label(btn);
|
||||
btn.hidden = false;
|
||||
btn.addEventListener('click', function () {
|
||||
root.dataset.theme = current() === 'dark' ? 'light' : 'dark';
|
||||
try { localStorage.setItem('theme', root.dataset.theme); } catch (e) {}
|
||||
label(btn);
|
||||
});
|
||||
media.addEventListener('change', function () { label(btn); });
|
||||
});
|
||||
})();
|
||||
Reference in New Issue
Block a user