This code is meant to detect if a user has a previously chosen color theme, and if not it should check whether they have dark mode enabled and set that corresponding theme, otherwise just set the theme to light mode. However, when I load up the page in incognito mode (so there's no localStorage data), no color theme loads. And when I go to a page with different code (code with the localStorage part but no matchMedia), choose a color theme, and go back to this page, that color theme doesn't show up either. I think there might be a simple syntax error because the code looks fine but it doesn't work for some reason.
function setTheme(themeName) {
localStorage.setItem('theme', themeName);
document.documentElement.className = themeName;
}
(function() {
if (localStorage.getItem('theme')) {
setTheme(localStorage.getItem('theme'))
} else {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
if (event.matches) {
setTheme('theme-simple-dark')
} else {
setTheme('theme-simple-light')
}
})
}
}());
In line with my comments, here's the reworked code. I also did a bit of DRYing up. Again, I have not tested it, may contain errors. setTheme is unchanged from yours.
function setThemeBool(dark) {
if (dark) {
setTheme('theme-simple-dark');
} else {
setTheme('theme-simple-light');
}
}
(function() {
const storedTheme = localStorage.getItem('theme');
const themeQuery = window.matchMedia('(prefers-color-scheme: dark)');
// is anything stored from before?
if (storedTheme) {
// yes, use that
setTheme(storedTheme);
} else {
// no, ask the browser
setThemeBool(themeQuery.matches);
}
// regardless, from now on, if the theme changes, switch accordingly
themeQuery.addEventListener('change', event => {
setThemeBool(event.matches);
});
}());