dimanche 11 octobre 2020

Save a dark mode checkbox toggle to local storage

On my website I have a checkbox, which toggles between a default light theme and a dark one. If the page is set to dark mode and refreshed, the theme is switched back to light mode. Is there a way to save the visitors decision, so the page stays in dark mode on refresh? This is the code I currently have:

const chk = document.getElementById('chk');

chk.addEventListener('change', () => {
    document.body.classList.toggle('dark');
});
body {
  background: #f5f5f5;
  color: #353535;
}

body.dark {
  background-color: #1a1a1a;
  color: #f5f5f5;
}
        <div class="toggle">
            <input type="checkbox" class="checkbox" id="chk" />
            <label class="label" for="chk">
        </div>
        <h1>website text</h1>

I realise it might be a simple answer, but i am new to web development, and am struggling to find answers myself. Thank in advance you for all your help.




Aucun commentaire:

Enregistrer un commentaire