javascripthtmlcsslocal-storage

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">Dark</label>
</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.


Solution

  • const chk = document.getElementById('chk');
    
    chk.addEventListener('click', () => {
      chk.checked ? document.body.classList.add("dark") : document.body.classList.remove("dark");
      localStorage.setItem('darkModeStatus', chk.checked);
    });
    
    window.addEventListener('load', (event) => {
      if (localStorage.getItem('darkModeStatus') == "true") {
        document.body.classList.add("dark");
        document.getElementById('chk').checked = true;
      }
    });
    body {
      background: #f5f5f5;
      color: #353535;
      text-align: right;
    }
    
    body.dark {
      background-color: #1a1a1a;
      color: #f5f5f5;
    }
    <div class="toggle">
      <input type="checkbox" class="checkbox" id="chk" />
      <label class="label" for="chk">Turn On Dark Mode</label>
    </div>
    <h1>Website Content</h1>