Reputation: 1
I just added a dark mode and currency switcher using JS, but the changes don't save after refreshing the page. Does somebody know how to use localStorage on the following codes? Changes can be seen on the following website Morocco tours.
Dark theme:
var icon = document.getElementById("icon-phone");
icon.onclick = function () {
document.body.classList.toggle("dark-theme");
if (document.body.classList.contains("dark-theme")) {
icon.src = "./assets/images/sun.png";
} else {
icon.src = "./assets/images/moon.png";
}
}
var icon = document.getElementById("icon");
icon.onclick = function () {
document.body.classList.toggle("dark-theme");
if (document.body.classList.contains("dark-theme")) {
icon.src = "./assets/images/sun.png";
} else {
icon.src = "./assets/images/moon.png";
}
}
Upvotes: 0
Views: 79
Reputation: 760
You can use localStorage.setItem('key', 'value')
to set and localStorage.getItem('key')
to read a localStorage item.
You could, for example, set localStorage.setItem('dark-theme', true)
and later retrieve it with localStorage.getItem('dark-theme')
.
var isDarkTheme = window.localStorage.getItem('dark-theme');
if (isDarkTheme === null) {
isDarkTheme = false;
} else {
isDarkTheme = isDarkTheme === 'true'
}
var icon = document.getElementById("icon-phone");
if (isDarkTheme) {
document.body.classList.add('dark-theme')
}
icon.onclick = function () {
isDarkTheme = !isDarkTheme;
if (isDarkTheme) {
document.body.classList.add('dark-theme');
} else {
document.body.classList.remove('dark-theme');
}
window.localStorage.setItem('dark-theme', isDarkTheme);
if (document.body.classList.contains("dark-theme")) {
icon.src = "./assets/images/sun.png";
} else {
icon.src = "./assets/images/moon.png";
}
}
Upvotes: 2