Skip to content
Advertisement

HTML Local Storage Dark Mode Using JavaScript

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:

function darkmode() {
    var element = document.body;
    element.classList.toggle("dark-mode");
}
<html>
<head>
<style>
.card {
  background-color: red;
  color: green;
}
.dark-mode .card {
  background-color: black;
  color: white;
}


</style>
</head>
<body>
<button onclick="darkmode()">DARK MODE</button>
<div class="card">
  <h2>Title</h2>
  <div class="fkimg" style="height: 100px; width: 20%;">IMAGE</div>
  <a>Some text</a>
</div>

</body>
</html>

Advertisement

Answer

For your sample code, it seems like the best approach would be to add something to the darkmode function:

function darkmode() {
  // all values retrieved from localStorage will be strings
  const wasDarkmode = localStorage.getItem('darkmode') === 'true';
  localStorage.setItem('darkmode', !wasDarkmode);
  const element = document.body;
  element.classList.toggle('dark-mode', !wasDarkmode);
}

function onload() {
  document.body.classList.toggle('dark-mode', localStorage.getItem('darkmode') === 'true');
}
<html>
<head>...</head>
<body onload="onload()">
  ...
</body>
</html>

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement