I'm currently building a music blog which uses the following JavaScript code to toggle dark mode / light mode buttons:
function swapStylesheet(sheet) {
document.getElementById('swap').setAttribute('href', sheet);
}
My issue is that the website reverts back to the default CSS sheet whenever the page is refreshed or a new page is visited, instead of remembering the chosen theme. Might I be able to have my website remember the user's last chosen theme via cookies or localstorage or something else?
Please let me know! Thank you so much. =]
Short answer is yes. You could save it via Cookies or Local Storage, and there's many ways to achieve this, I'll just give you reference for cookies, you could test it on W3School
The question you gave right now is only for between pages, but in cases that you want it to retain based on user accounts, then the answer is you need to centralize the "Theme" data for each account somewhere like Database or Server Cache.
https://www.w3schools.com/js/js_cookies.asp
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
checkCookie();