Repository navigation
Expand file tree
/
Copy paththeme.js
More file actions
39 lines (35 loc) · 1.54 KB
/
Copy paththeme.js
File metadata and controls
39 lines (35 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Theme toggle + persistence across pages.
// The chosen theme is stored in localStorage under "theme" and re-applied on
// every page load, so dark/light carries over as you navigate the site.
// (localStorage is per-origin and persists on the deployed HTTPS site and on
// file:// in Chrome/Edge/Firefox; storage access is wrapped so a browser that
// blocks it — e.g. private mode / strict settings — degrades gracefully rather
// than breaking the toggle.)
(function () {
var STORAGE_KEY = 'theme';
var DEFAULT_THEME = 'dark';
var root = document.documentElement;
function save(theme) {
try { localStorage.setItem(STORAGE_KEY, theme); } catch (e) { /* storage blocked */ }
}
function load() {
try { return localStorage.getItem(STORAGE_KEY); } catch (e) { return null; }
}
function apply(theme) {
root.setAttribute('data-theme', theme);
}
// Exposed globally for the nav toggle button (onclick="toggleTheme()").
window.toggleTheme = function () {
root.classList.add('transition'); // smooth colour transition
var next = root.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
apply(next);
save(next);
setTimeout(function () { root.classList.remove('transition'); }, 750);
};
// Apply the saved theme immediately (this script is in <head>) to avoid a flash.
apply(load() || DEFAULT_THEME);
// If the theme changes in another open tab, mirror it here live.
window.addEventListener('storage', function (e) {
if (e.key === STORAGE_KEY && e.newValue) apply(e.newValue);
});
})();