so my website is dark mode by default and i have added a light mode button to make the website light and i want the light mode to stay when switching pages, how can i make the light mode stay when switching pages. JS
//light mode for home page
function lightMode() {
var element = document.body;
element.classList.toggle("light-mode");
var buttonText = document.getElementById('lightModeButton');
if (buttonText.innerHTML === "Light") {
buttonText.innerHTML = "Dark";
}
else {
buttonText.innerHTML = "Light"
}
var footerLight = document.getElementById('footer');
footerLight.classList.toggle("footer-color");
footerLight.classList.toggle("footer-color a");
}
// light mode function for my information page
function lightModeInformation() {
var textInfo = [document.getElementById('textInformation'), document.getElementById('textInformation2'), document.getElementById('h1Information')];
textInfo[0].classList.toggle("text-when-light");
textInfo[1].classList.toggle("text-when-light");
textInfo[2].classList.toggle("text-when-light");
var element = document.body;
element.classList.toggle("light-mode");
var buttonText = document.getElementById('lightModeButton');
if (buttonText.innerHTML === "Light") {
buttonText.innerHTML = "Dark";
}
else {
buttonText.innerHTML = "Light"
}
var footerLight = document.getElementById('footer');
footerLight.classList.toggle("footer-color");
footerLight.classList.toggle("footer-color a");
}
i tried using if statements but it didnt work
I'd suggest saving the information about whether a user uses light or dark mode in the
localStorage
. You can access this variable from thelocalStorage
on each of your sites from the same domain. It also persists sessions, if you don't delete it manually.e.g. set the mode like
localStorage.setItem('mode', 'light');
and refer to it likeconst mode = localStorage.getItem('mode');
Check out the docs.