I'm in the process of implementing a dark mode for my website using the code below. However, I've encountered an issue where the dark mode resets when refreshing the page or navigating to a new page. I've heard about a feature called localstorage
in JavaScript that might help with this problem. If anyone is familiar with it, could you please share the method to resolve this?
<style>
body {background-color: white}
body.dark {background-color: black}
button {background-color: white; color: black}
body.dark button {background-color: black; color: white}
</style>
<script>
function toggleDark() {
const body = document.querySelector('body');
if (body.classList.contains('dark')) {
body.classList.remove('dark');
} else {
body.classList.add('dark');
}
}
document.querySelector('#darkmode').addEventListener('click', toggleDark);
</script>
<button id="darkbutton" class="darkmode" onclick="toggleDark();myFunction()">Toggle dark mode</button>