Update theme color onClick

This commit is contained in:
madrilene 2024-06-25 15:18:00 +02:00
parent ff75f1543a
commit d23bc96fce

View file

@ -20,7 +20,7 @@ window.onload = () => {
} }
reflectPreference(); reflectPreference();
updateThemeColor(); updateMetaThemeColor();
lightThemeToggle.addEventListener('click', () => onClick('light')); lightThemeToggle.addEventListener('click', () => onClick('light'));
darkThemeToggle.addEventListener('click', () => onClick('dark')); darkThemeToggle.addEventListener('click', () => onClick('dark'));
@ -33,6 +33,7 @@ window.onload = () => {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', ({matches: isDark}) => { window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', ({matches: isDark}) => {
theme.value = isDark ? 'dark' : 'light'; theme.value = isDark ? 'dark' : 'light';
setPreference(); setPreference();
updateMetaThemeColor();
}); });
function onClick(themeValue) { function onClick(themeValue) {
@ -40,6 +41,7 @@ function onClick(themeValue) {
document.querySelector('#light-theme-toggle').setAttribute('aria-pressed', themeValue === 'light'); document.querySelector('#light-theme-toggle').setAttribute('aria-pressed', themeValue === 'light');
document.querySelector('#dark-theme-toggle').setAttribute('aria-pressed', themeValue === 'dark'); document.querySelector('#dark-theme-toggle').setAttribute('aria-pressed', themeValue === 'dark');
setPreference(); setPreference();
updateMetaThemeColor();
} }
function getColorPreference() { function getColorPreference() {
@ -53,6 +55,7 @@ function getColorPreference() {
function setPreference() { function setPreference() {
localStorage.setItem(storageKey, theme.value); localStorage.setItem(storageKey, theme.value);
reflectPreference(); reflectPreference();
updateMetaThemeColor();
} }
function reflectPreference() { function reflectPreference() {
@ -61,10 +64,12 @@ function reflectPreference() {
document.querySelector('#dark-theme-toggle')?.setAttribute('aria-label', darkLabel); document.querySelector('#dark-theme-toggle')?.setAttribute('aria-label', darkLabel);
} }
function updateThemeColor() { function updateMetaThemeColor() {
document console.log('Updating theme color to:', theme.value);
.querySelector('meta[name="theme-color"]') const metaThemeColor = document.querySelector('meta[name="theme-color"]');
.setAttribute('content', theme.value === 'dark' ? themeColors.dark : themeColors.light); const newColor = theme.value === 'dark' ? themeColors.dark : themeColors.light;
console.log('New meta theme color:', newColor);
metaThemeColor.setAttribute('content', newColor);
} }
// set early so no page flashes / CSS is made aware // set early so no page flashes / CSS is made aware