first template launch (#2)
Co-authored-by: Michael DiLeo <michael.dileo@oakstreethealth.com> Reviewed-on: #2
This commit was merged in pull request #2.
This commit is contained in:
73
public/site-scripts/theme-toggle.js
Normal file
73
public/site-scripts/theme-toggle.js
Normal file
@@ -0,0 +1,73 @@
|
||||
(function() {
|
||||
const themeToggle = document.getElementById('theme-toggle');
|
||||
const themeIcon = document.getElementById('theme-icon');
|
||||
|
||||
function getStoredTheme() {
|
||||
return localStorage.getItem('picoPreferredColorScheme') || 'auto';
|
||||
}
|
||||
|
||||
function storeTheme(theme) {
|
||||
localStorage.setItem('picoPreferredColorScheme', theme);
|
||||
}
|
||||
|
||||
function getSystemTheme() {
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
|
||||
function applyTheme() {
|
||||
const storedTheme = getStoredTheme();
|
||||
let actualTheme;
|
||||
|
||||
if (storedTheme === 'auto') {
|
||||
actualTheme = getSystemTheme();
|
||||
} else {
|
||||
actualTheme = storedTheme;
|
||||
}
|
||||
|
||||
document.documentElement.setAttribute('data-theme', actualTheme);
|
||||
|
||||
if (actualTheme === 'dark') {
|
||||
themeIcon.textContent = '☀️';
|
||||
themeToggle.setAttribute('aria-pressed', 'true');
|
||||
} else {
|
||||
themeIcon.textContent = '🌙';
|
||||
themeToggle.setAttribute('aria-pressed', 'false');
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTheme() {
|
||||
const currentStored = getStoredTheme();
|
||||
let nextTheme;
|
||||
|
||||
if (currentStored === 'auto') {
|
||||
nextTheme = 'light';
|
||||
} else if (currentStored === 'light') {
|
||||
nextTheme = 'dark';
|
||||
} else {
|
||||
nextTheme = 'auto';
|
||||
}
|
||||
|
||||
storeTheme(nextTheme);
|
||||
applyTheme();
|
||||
}
|
||||
|
||||
function init() {
|
||||
if (themeToggle) {
|
||||
applyTheme();
|
||||
|
||||
themeToggle.addEventListener('click', toggleTheme);
|
||||
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
|
||||
if (getStoredTheme() === 'auto') {
|
||||
applyTheme();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (document.readyState !== 'loading') {
|
||||
init();
|
||||
} else {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
}
|
||||
})();
|
||||
Reference in New Issue
Block a user