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

86
Vistas
Storing Class name in HTML localStorage

I am trying to use a theme selector that adds "dark" class name to HTML element.

like: <html class="dark">

I want to save class name in localStorage so it will be consistent even after page reload.

Here is my JS

(function () {
  window.__onThemeChange = function () { };
  function setTheme(newTheme) {
    window.__theme = newTheme;
    preferredTheme = newTheme;
    document.documentElement.setAttribute('class', newTheme);
    window.__onThemeChange(newTheme);
  }

  var preferredTheme;
  try {
    preferredTheme = localStorage.getItem('theme');
  } catch (err) { }

  window.__setPreferredTheme = function (newTheme) {
    setTheme(newTheme);
    try {
      localStorage.setItem('theme', newTheme);
    } catch (err) { }
  }

  var darkQuery = window.matchMedia('(prefers-color-scheme: light)');

  darkQuery.addListener(function (e) {
    window.__setPreferredTheme(e.matches ? 'light' : 'dark');
  });

  setTheme(preferredTheme || (darkQuery.matches ? 'light' : 'dark'));
})();

Any idea how to correctly to save the class="dark" in localStorage?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

What I'm seeing here is that in the function __setPreferredTheme you're stringifying a value 'light' or 'dark' and then parsing out this value in the variable preferredTheme, which causes an error cause you're parsing a string. You should be able to just pass the value of the class in the function without using parse or stringify.

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