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

192
Views
Where should I put the localStorage in this code?

I am trying to make the dark/light mode theme on my site store locally so that it doesnt untoggle every time a new page is opened or the site is refreshed. Where should I put the localStorage.? Or is the whole thing wrong?

const checkbox = document.getElementById('checkbox');
        
        checkbox.addEventListener('change',()=> {
          // change theme of website
          document.body.classList.toggle('dark');
        });
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

if you're using vanilla javascript i.e on you html you've loaded your script as below

<html>
...

<script src='/to/scripts.js'></script>
</body>
</html>

Then you can add two functions, one which set the them to localStorage and the other which reads it and make it accessible.

on update the update function sets the new value for the theme, on read the read function reads the stored value even after refresh/reloads as below

<html>
  ....
 <script>
  //for setting
   const toggleTheme = () => {
      if(localStorage.getItem('theme') === 'dark'){
         localStorage.setItem('theme','light')
      }else{
          localStorage.setItem('theme','dark')
       }
   }
  //for reading
   const theme = () => localStorage.getItem('theme') || 'light'
 </script>

 <script src='/to/scripts.js'></script>
 </body>
 </html>
about 4 years ago · Juan Pablo Isaza Report

0

Edit (last answer was not solving the problem)

I think you can use DOMContentLoaded event to set the theme from localStorage, when the checkbox changes you set the selected theme on the storage. This way when the page reloads, it will look for the theme and set it, if theme is not set, it will default to light.

Here is a sample:

document.addEventListener("DOMContentLoaded", function(event) {
  const theme = localStorage.getItem('theme');
  if(theme === undefined) theme = 'light';
  document.body.classList.add(theme);
});

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

checkbox.addEventListener('change',(e) => {
    const theme = e.target.checked ? 'dark' : 'light';
  localStorage.setItem(theme);
  document.body.classList.add(theme);
});

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!