Jima Victor
webcodespace

webcodespace

How to add dark mode using javascript

Jima Victor's photo
Jima Victor
·Jun 29, 2022·

4 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

We're going to be adding dark mode to a simple website using javascript and the localStorage property of the window object.

The localStorage property will be used in order to maintain dark mode even after the page is refreshed.

Note: Before we start, I'd like to say that the best way to gain a lot from this tutorial is by following along, especially if you are a beginner.. (though it's not necessary, it's better if you could).

Some fun facts about localstorage

  1. localStorage is quite similar to sessionStorage; the difference is that in sessionStorage, data is cleared whenever a session ends (a tab or window is closed) while in localStorage, data is retained even after the end of a session.
  2. It stores data in key value pairs like in JSON format.
  3. localStorage for a private tab is cleared when the last private tab is closed.
  4. localStorage size is limited to 5MB per app per browser
  5. It can only store strings.

Let's begin...

  • Create an index.html file and copy the following html code into it.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>dark mode</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="box">i am a box</div>
    <button class="switch">toggle dark mode</button>
    <script src="darkmode.js"></script>
  </body>
</html>

So for the above html code, what we did is link our html file with our style.css and darkmode.js files. We also created a box with some text and a button to enable us switch dark mode.

  • Create a style.css file and copy the following code into it.

body {
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.box {
  height: 100px;
  width: 100px;
  background-color: black;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}
.darkMode {
  background-color: black;
}
.darkMode > .box {
  background-color: white;
  color: black;
}

In our style.css file:

  • We first set the height and width of our body element and centered our box div in the body using flexbox. We also change the flex-direction from row to column to make it look prettier.

  • Secondly, we set height and width of our box div, gave it a background color and centered the text inside of it using flexbox. We also added a margin bottom to it so as to create a little space between the box and the button

  • We also added some styles for our dark mode but it doesn't have any effect on the page yet, as we are going to activate it using javascript.
  • Create the darkmode.js file and add the following code to it.

let darkMode = localStorage.getItem("darkMode");

if (darkMode == "true") {
  addDarkMode();
}
document.querySelector(".switch").addEventListener("click", function () {
  darkMode = localStorage.getItem("darkMode");
  if (darkMode == "true") {
    removeDarkMode();
  } else {
    addDarkMode();
  }
});

function addDarkMode() {
  darkMode = localStorage.setItem("darkMode", "true");
  document.getElementsByTagName("body")[0].classList.add("darkMode");
}

function removeDarkMode() {
  darkMode = localStorage.setItem("darkMode", "false");
  document.getElementsByTagName("body")[0].classList.remove("darkMode");
}

Here's what we did in the javascript code.

  1. We first try to get the value for the dark mode using the getItem() method. The getItem() method takes a key as its argument and returns the value for that key (if it is set) or null (if it is not).
  2. The next thing we did, was to check if the value is set to true, and if it is, we call the addDarkMode() function which updates the value of the darkMode variable (the variable was declared at the top using the let keyword, so it can be updated) by setting the value of the darkMode key to true using the setItem() method. The first argument of the setItem() method is the key, while the second argument is its value. Then we add the darkMode class to the body element. So those CSS styles under the darkMode class can be added.
  3. The final thing we did, was to add a click event listener to our button after it has been queried from the DOM, we fetch the value of the darkMode from the localStorage and check if it is true, so we can call our addDarkMode() function or false so we can call our removeDarkMode() function. The removeDarkMode() function is the same with the addDarkMode() function; the only difference is that the removeDarkMode() function removes the darkMode class from the body element while the addDarkMode() function adds it.

Once you've clicked the switch button, the value for the dark mode is set and will always be remembered by the browser even when the page is refreshed or at the end of a session. This is the reason why we try to get the value of darkMode at the top of our javascript code. So that once the page reloads, or we visit our website again, It will first get the value that we have set previously and set the dark mode depending on what the value of the key may be (true or false).

 
Share this