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

85
Visualizações
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 Respostas
Responde à pergunta

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 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