I tried to make a complete darkmode to my website. It’s almost done, but I have an issue. When I reload the page the dark mode goes back to the default light mode. How can I sovle this problem? I tried some code but it didn’t work. I want to use Local Storage, but I don’t know how to add it to my code. Can someone help me with this? Here is my sample code:
JavaScript
x
4
1
function darkmode() {
2
var element = document.body;
3
element.classList.toggle("dark-mode");
4
}
JavaScript
1
25
25
1
<html>
2
<head>
3
<style>
4
.card {
5
background-color: red;
6
color: green;
7
}
8
.dark-mode .card {
9
background-color: black;
10
color: white;
11
}
12
13
14
</style>
15
</head>
16
<body>
17
<button onclick="darkmode()">DARK MODE</button>
18
<div class="card">
19
<h2>Title</h2>
20
<div class="fkimg" style="height: 100px; width: 20%;">IMAGE</div>
21
<a>Some text</a>
22
</div>
23
24
</body>
25
</html>
Advertisement
Answer
For your sample code, it seems like the best approach would be to add something to the darkmode
function:
JavaScript
1
12
12
1
function darkmode() {
2
// all values retrieved from localStorage will be strings
3
const wasDarkmode = localStorage.getItem('darkmode') === 'true';
4
localStorage.setItem('darkmode', !wasDarkmode);
5
const element = document.body;
6
element.classList.toggle('dark-mode', !wasDarkmode);
7
}
8
9
function onload() {
10
document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');
11
}
12
JavaScript
1
7
1
<html>
2
<head></head>
3
<body onload="onload()">
4
5
</body>
6
</html>
7
MDN localStorage reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage