quantvat / src /static /js /theme.js
heisbuba's picture
Upload theme.js
6bc2e5e verified
Raw History Blame
1.43 kB
(function () {
var KEY = 'qv-theme';
var root = document.documentElement;
var btn = document.getElementById('theme-toggle');
var meta = document.querySelector('meta[name="theme-color"]');
function current() {
return root.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
}
function apply(theme) {
if (theme === 'light') root.setAttribute('data-theme', 'light');
else root.removeAttribute('data-theme');
if (meta) meta.setAttribute('content', getComputedStyle(root).getPropertyValue('--bg-dark').trim());
if (!btn) return;
var next = theme === 'light' ? 'dark' : 'light';
btn.setAttribute('aria-pressed', String(theme === 'light'));
btn.setAttribute('aria-label', 'Switch to ' + next + ' theme');
btn.setAttribute('title', 'Switch to ' + next + ' theme');
}
function save(theme) {
try {
if (theme === 'light') localStorage.setItem(KEY, 'light');
else localStorage.removeItem(KEY);
} catch (e) {}
}
apply(current());
if (btn) {
btn.addEventListener('click', function () {
var theme = current() === 'light' ? 'dark' : 'light';
apply(theme);
save(theme);
});
}
window.addEventListener('storage', function (e) {
if (e.key === KEY) apply(e.newValue === 'light' ? 'light' : 'dark');
});
})();