Estoy usando la casilla de verificación para alternar el color del tema negro y oscuro usando HTML, CSS y JS. Tengo este código dentro de mi barra de navegación. Está funcionando bien. Pero una vez actualizado o cambiado a otras páginas dentro del sitio web, ya no permanece oscuro.
<div> <input type="checkbox" class="checkbox" id="chk" /> <label class="label" for="chk"> <i class="fas fa-moon"></i> <i class="fas fa-sun"></i> <div class="ball"></div> </label> </div>Alguien sugirió el concepto de usar almacenamiento local y probé esto, pero no funciona.
const chk = document.getElementById('chk'); chk.addEventListener('change', () => { document.body.classList.toggle('dark'); }); // for checkbox remained checked document.getElementById('chk')(function(){ var test = localStorage.input === 'true'? true: false; document.getElementById('chk')('input').prop('checked', test || false); }); document.getElementById('chk')('input').on('change', function() { localStorage.input = document.getElementById('chk')(this).is(':checked'); console.log(document.getElementById('chk')(this).is(':checked')); });Por favor, que alguien me ayude.
PD: No soy un desarrollador web. Uso HTML y CSS de aquí y de allá para mi blog. Estoy usando páginas de GitHub para alojar mi sitio web. https://amatya-aditya.github.io/
Hubo algunos problemas con la sintaxis del código JavaScript. Consulte a continuación el código actualizado.
nota: document.getElementById() no devuelve una función
const chk = document.getElementById('chk'); chk.addEventListener('change', (e) => { localStorage.setItem('dark-mode', e.target.checked); if ( e.target.checked ) document.body.classList.add('dark'); else document.body.classList.remove('dark'); }); window.addEventListener('load', () => { let value = localStorage.getItem('dark-mode'); document.getElementById('chk').checked = value === 'true' ? true : false; if ( value === 'true' ) document.body.classList.add('dark'); else document.body.classList.remove('dark'); })