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');
});
CodePudding user response:
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>
CodePudding user response:
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);
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>