HTML Local Storage Dark Mode Using JavaScript

Tags: , , , ,

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;
.card {
  background-color: red;
  color: green;
.dark-mode .card {
  background-color: black;
  color: white;

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



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');
<body onload="onload()">

MDN localStorage reference:

Source: stackoverflow