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

250
Vistas
Local storage not working properly for JS onclick

My local storage works in terms of saying true and false, but when the page is refreshed, it reverts but keeps the value. For example, if I switch from default darkmode (false) to lightmode (true), it shows as true in the local storage (which is good). However, when I refresh the page, although the value still is true, the page has reverted to its default (false).

HTML:

<body onload="stored()">
  <label for="ID_HERE" class="toggle-switchy">
    <input checked type="checkbox" name="server" id="ID_HERE" />
    <span class="toggle" onclick="toggle()" id="saveDarkLight"></span>
    <span class="switch"></span>
  </label>
</body>

JS:

function stored() {
  var storedValue = localStorage.getItem("server");
  if (storedValue) {
    lightmode()
    document.getElementById("ID_HERE").checked = true;
  } else {
    darkmode()
    document.getElementById("ID_HERE").checked = false;
  }
}

function toggle() {
  if (document.getElementById("ID_HERE").checked) {
    lightmode()
    var input = document.getElementById("ID_HERE");
    localStorage.setItem("server", input.checked);
  }
  else {
    darkmode()
    var input = document.getElementById("ID_HERE");
    localStorage.setItem("server", input.checked);
  }
}

function darkmode() {
  const bodyChanges = document.querySelectorAll('.margin_body');
  for (let i = 0; i < bodyChanges.length; i++) {
    bodyChanges[i].style.background = '#0c0a0f';
  }
}

function lightmode() {
  const bodyChanges = document.querySelectorAll('.margin_body');
  for (let i = 0; i < bodyChanges.length; i++) {
    bodyChanges[i].style.background = 'white';
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

localStorage only saves string values, so saving true or false will convert it to 'true' or 'false'. When you read back, you need to either JSON.parse it or check against the string values.

function stored() {
    const storedValue = localStorage.getItem("server");
    if(storedValue === 'true'){  // <------
        lightmode()
        document.getElementById("ID_HERE").checked = true;
    }else{
        darkmode()
        document.getElementById("ID_HERE").checked = false;
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

First and foremost, I think you'll want the onclick event handler on the input element.

Also, the following is a quick and dirty implementation:

JS:

const SAVED_USER_INPUT = "savedUserInput";
const TARGET_ID = "toggle-text";
const BLUE = "blue";
const RED = "red";
const text = {
  [BLUE]:
    "Text color currently set to blue (default/unchecked state). Click to change to red",
  [RED]: "Text color currently set to red. Click to change to blue",
};

const handleToggle = (event) => {
  const isChecked = event.target.checked;
  const color = isChecked ? RED : BLUE;
  setColor(color);
  setText(color);
  savePreference(color);
};

const setColor = (fontColor = BLUE) => {
  document.getElementById(TARGET_ID).style.color = fontColor;
  return true;
};
const setText = (color) => {
  document.getElementById(TARGET_ID).innerText = text[color];
  return true;
};
const setChecked = (color) => {
  if (color === RED) {
    document.getElementsByTagName("input")[0].setAttribute("checked", true);
  }
};
const savePreference = (color) => localStorage.setItem(SAVED_USER_INPUT, color);
const getSavedPreference = () => localStorage.getItem(SAVED_USER_INPUT);
// localStorage.clear()
window.onload = () => {
  if (!(getSavedPreference() === null)) {
    const savedColor = getSavedPreference();
    setColor(savedColor);
    setText(savedColor);
    setChecked(savedColor);
  } else {
    setColor();
    setText(BLUE);
    setChecked(BLUE);
  }
};

HTML:

<!DOCTYPE html>
<html>

<head>
    <title>localStorage</title>
    <script src="app.js"></script>
</head>

<body>
    <label>
        <input type="checkbox" onclick="handleToggle(event)">
        <span id="toggle-text"></span>
        </span>
    </label>
</body>

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