Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

295
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda