Reputation: 127
I am trying to use the W3Schools Toggle Switch for my website Dark/Light Mode Toggle.
This is my Website Test Page in which I have added the Toggle Switch but the thing which happens is that the switch is not able to save it's "on/off" mode when the page is refreshed.
It restores back to it's default "Off" mode when I refresh the Page.
How can I save it's position on Page Refresh?
Upvotes: 0
Views: 2678
Reputation: 569
First update below code on "// On page load se the theme." section
var tSwitcher = document.getElementById('theme-switcher');
let element = document.body;
let onpageLoad = localStorage.getItem("theme") || "";
if(onpageLoad != null && onpageLoad == 'dark-mode'){
tSwitcher.checked = true;
}
element.classList.add(onpageLoad);
function themeToggle(){
if(tSwitcher.checked){
localStorage.setItem('theme', 'dark-mode');
element.classList.add('dark-mode');
} else {
localStorage.setItem('theme', '');
element.classList.remove('dark-mode');
}
}
and change
<input type="checkbox" onclick="themeToggle()">
to
<input type="checkbox" onclick="themeToggle()" id="theme-switcher">
Upvotes: 2
Reputation: 410
you can store the status of toggle (on or off into localstorage) and get the value from localstorage.
Upvotes: 0