I’m trying to implement a localStorage for my dark mode, but I can’t do it, whats the best way to do it so?
Here is my working JS / Html code, what I need is no
JavaScript
x
11
11
1
<div class="mode-switch">
2
<button class="mode magic-hover" id="menu-btn" onclick="theme()"></button>
3
</div>
4
<script>
5
function theme() {
6
var element = document.body;
7
element.classList.toggle("darkmode");
8
}
9
<script>
10
11
Advertisement
Answer
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
To set it:
JavaScript
1
7
1
function theme() {
2
var element = document.body;
3
element.classList.toggle("darkmode");
4
let newmode = element.classList.contains('darkmode') ? 'darkmode' : 'lightmode';
5
localStorage.setItem('mode', newmode)
6
}
7
to get it
JavaScript
1
5
1
window.onload = function() {
2
let newmode = localStorage.getItem('mode') || "";
3
document.body.classList.add(newmode);
4
}
5