Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
Establecer tema de color con localStorage

Tengo un sistema de temas de color configurado en mi sitio. Cuando hace clic en un botón, se agrega una clase a <html> y su tema correspondiente entra en vigor. Sin embargo, cuando cargo mi sitio por primera vez (utilizo el modo de incógnito para simular esto), ninguno de los temas funciona. Quiero volver a escribir un bloque de mi código para decir básicamente: "Cuando no haya nada en localStorage, cargue 'theme-dark-blue'".

Aquí está mi código:

 // function to set a given theme/color-scheme function setTheme(themeName) { localStorage.setItem('theme', themeName); document.documentElement.className = themeName; } // Immediately invoked function to set the theme on initial load (function () { if (localStorage.getItem('theme') === 'theme-dark-blue') { setTheme('theme-dark-blue'); } })();

Los otros temas hasta ahora son 'theme-light-blue' y 'theme-dark-green'. Estaba pensando en intentar expresarlo como "Si <html> no tiene una clase, establezca 'theme-dark-blue'"

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

 function setTheme(themeName) { localStorage.setItem('theme', themeName); document.documentElement.className = themeName; } // Immediately invoked function to set the theme on initial load (function () { if (localStorage.getItem('theme')) { setTheme(localStorage.getItem('theme')) } else { setTheme('theme-dark-blue') } })();

Aquí verificamos si el elemento en los almacenamientos locales existe, si existe, lo usamos, si no, establecemos la clase de tema predeterminada

about 4 years ago · Juan Pablo Isaza Report

0

Esto es lo que tenemos que hacer

  1. Obtener el valor del localStorage
  2. Comprueba que es válido
  3. Si el valor no es válido o falta, utilice el valor predeterminado

 const validTheme = ['theme-dark-blue', 'theme-dark-green']; const getThemeFromLocalStorage = () => { const savedTheme = localStorage.getItem('theme'); return validTheme.includes(savedTheme) ? savedTheme : null; }; setTheme(getThemeFromLocalStorage() || 'theme-dark-blue');
about 4 years ago · Juan Pablo Isaza Report

0

Mejor conjetura.

Hasta donde yo sé, si intentas setItem() algo que se eliminó del almacenamiento local o no existe, entonces la respuesta de retorno es nula.

Entonces, tal vez encuentre una forma de codificar: "Si se agrega una clase a mi HTML, cree un setItem() con el mismo nombre que esa nueva clase y agréguelo a localMemory". Si la clase existe en la memoria local, getItem() lo confirmará. Si no es así, getItem() devolverá nulo.

Así que crea tu declaración if diciendo: "If getItem(className) = null, then set theme-dark-blue"

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!