Skip to content
Advertisement

Implement localStorage to save Dark Mode Button Click and Class [closed]

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

<div class="mode-switch">
 <button class="mode magic-hover" id="menu-btn" onclick="theme()"></button>
</div>
<script>
 function theme() {
  var element = document.body;
    element.classList.toggle("darkmode");
 }
<script>
 

Advertisement

Answer

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

To set it:

function theme() {
  var element = document.body;
    element.classList.toggle("darkmode");
    let newmode = element.classList.contains('darkmode') ? 'darkmode' : 'lightmode';    
    localStorage.setItem('mode', newmode)
 }

to get it

window.onload = function() {
    let newmode = localStorage.getItem('mode') || "";
    document.body.classList.add(newmode);    
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement