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?