Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

310
Visualizações
My JS for detecting light/dark mode doesn't work right

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')
            }
        })
    }
}());
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
    });
}());
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda