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

281
Views
How do I configure localStorage for enabling dark mode?

I have a bare bones Astro project where I am using vanilla HTML, CSS, and JS. I am trying to enable the ability to toggle dark mode. I have a global.css file with root styles:

* {
  box-sizing: border-box;
  margin: 0;
}

:root {
  --primary: white;
  --text: black;
}

.darkmode {
  --primary: black;
  --text: white;
}

I then have a button component:

<button class="darkmode-toggle" aria-pressed="false">Enable Dark Mode</button>

<script>
  let darkmode = localStorage.getItem('darkmode');
  const systemPrefs = window.matchMedia('(prefers-color-scheme: dark)').matches;
  const darkmodeToggle = document.querySelector('.darkmode-toggle');

  const enableDarkmode = () => {
    document.documentElement.classList.add('darkmode');
    darkmodeToggle.textContent = 'Disable Dark Mode';
    darkmodeToggle.setAttribute('aria-pressed', 'true');

    localStorage.setItem('darkmode', 'enabled')
  }

  const disableDarkmode = () => {
    document.documentElement.classList.remove('darkmode')
    darkmodeToggle.textContent = 'Enable Dark Mode'
    darkmodeToggle.setAttribute('aria-pressed', 'false')

    localStorage.setItem('darkmode', null)
  }

  if (darkmode === 'enabled' || systemPrefs) enableDarkmode()

  darkmodeToggle.addEventListener('click', _ => {
    darkmode = localStorage.getItem('darkmode')

    darkmode !== 'enabled'
      ? enableDarkmode()
      : disableDarkmode()
  })
</script>

This implementation works which you will be able to see from this CodeSandbox. This issue I'm having is that when the page refreshes, the color goes back to the default.

I'm assuming this is usually fixed by using localStorage, which I am, making me think there's something off about my implementation. Where am I misusing localStorage?

about 4 years ago · Juan Pablo Isaza
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!