I'm new here (and coding, in general) but everyone says that once you have a question and you are unable to find the answer in Stackoverflow, you should ask, but I've always found that maybe the question was too dumb.
The thing is, I was trying to set a switcher for light-dark mode and it works fine, but once you refreshed the page, the theme change was not being saved. I found that using JavaScript you can store that change locally by using "localStorage.setItem()", but it's not working as I expected. I will try to provide as many details as I can:
- I have created two css classes for my body tag: 'dark' and 'light', each one with its own css variables for colors. Note: I do not have two body tags, it is just to show both classes I have to toggle between.
<body class='light'>(all the content)</body>
<body class='dark'>(all the content)</body>
- The change from one to the other is triggered by a switcher with a css class '.slider' on it, that gets called everytime it is clicked:
const switchBtn = document.querySelector('.slider');
switchBtn.addEventListener('click', () => {
if(document.body.classList.contains('light')) {
document.body.classList.replace('light', 'dark');
}
else
{
document.body.classList.replace('dark', 'light');
};
});
And until this point, everything changes from one to the other fine.
- At last, I added a way to try to store it locally by modifying/taking advantage (or that I thought) of the previous function:
let darkTheme = localStorage.getItem('dark');
switchBtn.addEventListener('click', () => {
darkTheme = localStorage.getItem('dark'); //Trying update the info stored about the darkTheme
if(document.body.classList.contains('light') && darkTheme == null) {
document.body.classList.replace('light', 'dark');
localStorage.setItem('darkTheme', 'enabled');
}
else
{
document.body.classList.replace('dark', 'light');
localStorage.setItem('darkTheme', null);
};
});
And at this point, I can see in Chrome's Application > Local Storage that every time I click, it does change the theme and it also changes the value of the key from 'enabled' to null and viceversa, but once I refresh the page, it returns to my 'light' theme, despite having the key still 'enabled'. In fact, at that point I can click to turn on the dark theme once again and, obviously, the value of the key remains the same; but if I click it again, as expected, it returns to the null value (light mode).
Thank you in advance for your help!