Dark Mode Toggle Button with Html, CSS, JavaScript in just 2 minutes

Dark Mode Toggle Button with Html, CSS, JavaScript in just 2 minutes

Adding a dark mode toggle button on a website is as popular as ever today, so here’s a simple way to do it with JavaScript. Once the HTML and JavaScript is in place, you can adjust the CSS as needed to create the two different themes (dark and light modes).

Benefits of Dark Mode

  • While the dark text on a white background is the best in terms of readability, Dark Mode which has light text on a dark background is better for reducing eye strain in low light conditions. In the long term, dark mode is less detrimental to the eyes than light mode.
  • In a low-light environment, the dark mode makes it easier for anybody to use a screen.
  • Dark Mode saves energy, especially if the computer uses an OLED or AMOLED display.

Dark mode/theme is gradually becoming one of the most used features on desktop/mobile devices. If you are on a browser, website, or any android applications, you will find the dark mode toggle switch at the right-hand corner of the application.

Dark mode will provide relaxation from a bright screen’s visual overstimulation or a more stable production environment with your smartphone or desktop applications. In this tutorial, we’ll show you how to add the dark mode feature to your web applications by using JavaScript so the users can toggle it as per their preference.

This tutorial assumes the reader has minimal knowledge of HTML, CSS, and JavaScript. For more experienced developers, skip through to select information as needed.

There are different ways of integrating this functionality on your websites or mobile applications. With a pinch of HTML, CSS styling, and JavaScript functions, we can implement the dark mode functionality. Before digging into the code, create a new project with three main files, such as darkMode.htmldarkMode.css, and darkMode.js to place all the HTMLCSS, and JavaScript codes respectively.

HTML Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Dark Mode</title>
    <!-- Necessary libraries and hyper-links for the website -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <!-- Bootstrap Library for responsiveness -->
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css"
    />
    <!-- Icon for the dark mode -->
    <script
      src="https://kit.fontawesome.com/91e547386c.js"
      crossorigin="anonymous"
    ></script>
    <!-- CSS reference for styling -->
    <link rel="stylesheet" href="darkMode.css" />
  </head>
  <body>
    <div class="outer">
      <div class="container">
        <!-- Dark Mode Icon -->
        <a>
          <i id="dark-mode-btn" class="toggler far fa-moon"></i>
        </a>
        <h1>Dark Mode</h1>
        <br />
        <h3>Purely coded with HTML, CSS and JavaScript.</h3>
        <br />
        <h4>Used Bootstrap library for responsiveness.</h4>
      </div>
    </div>
    <!-- JavaScript Referencing -->
    <script src="darkmode.js"></script>
  </body>
</html>

First, let’s write the HTML code required for this tutorial. For maintaining the coding standards, using HTML Boilerplate code is a must. In the darkMode.html file, add the following code.

It’s a simple HTML code that contains the outer division tag. The inner division contains a few header texts along with the toggler icon. For the moon icon to be visible, we need to add the font-awesome library. Include the kit in the head section of the web page. Rather than using the CSS internally, let’s define it in such a way that we can use it for many HTML pages. We call this External CSS. You can change the look of an entire website with an external style sheet just by modifying a single file.

Add a style sheet reference link in the head tag of the HTML page. Do the same with the JavaScript file as well. We can also place scripts in external files. Put the name of the script file in the src (source) attribute of the script tag to use an external script. This makes your code look neat and easily readable. Make sure the JavaScript and CSS files must have the file extension as .js and .css respectively.

HTML Output

Toggle Between Light Dark Mode

CSS Code

.body {
  padding: 10px;
}

.container {
  padding: 25px;
  background-color: #ffaa80;
  width: 100%;
  justify-content: center;
  align-items: center;
  border-radius: 25px;
}

.outer {
  padding: 25px;
  width: 100%;
  justify-content: center;
  align-items: center;
  border-radius: 25px;
}

h1,
h3,
h4 {
  color: white;
}

/* CSS styling for Dark-mode and light mode toggle */

i.toggler {
  color: white;
  float: right;
  font-size: 20px;
}

.dark-mode {
  background-color: black;
}

.dark-mode i.toggler {
  color: orange;
}

.dark-mode .container {
  background-color: white;
}

.dark-mode h1,
.dark-mode h3,
.dark-mode h4 {
  color: black;
}

/* End of CSS Styling for dark and light mode toggle */

Let’s add the CSS styling to our webpage. In the darkMode.css file, add the following code.

You Might Like This:

Design-wise it is correct, but functionally it’s not. When you click on the moon icon, there won’t be toggling from dark to light mode or vice versa. Because we have not yet added the core part of the feature, which is JavaScript.

CSS Output

Toggle Between Light Dark Mode2

JavaScript Code

function myFunction() {
  var element = document.body;
  element.classList.toggle("dark-mode");
}

var app = document.getElementsByTagName("BODY")[0];
if (localStorage.lightMode == "dark") {
  app.setAttribute("data-light-mode", "dark");
}

function toggle_light_mode() {
  var app = document.getElementsByTagName("BODY")[0];
  if (localStorage.lightMode == "dark") {
    localStorage.lightMode = "light";
    app.setAttribute("data-light-mode", "light");
  } else {
    localStorage.lightMode = "dark";
    app.setAttribute("data-light-mode", "dark");
  }
  console.log("lightMode = " + localStorage.lightMode);
}

document
  .getElementById("dark-mode-btn")
  .addEventListener("click", function (e) {
    const toggler = document.body;
    toggler.classList.toggle("dark-mode");
    const target = e.target;
    target.classList.toggle("fa-moon");
    target.classList.toggle("fa-sun");
  });

Last, let’s add a few JavaScript functions to toggle the dark and light mode feature. In the darkMode.js file, add the following code.

When we click on the moon icon, the above code helps in switching from light to a dark theme and vice versa. As soon as we enter the light mode, the icon now changes from sun to moon automatically. This will help users know the current status of the page without allowing them to switch back and fro to see the difference.

Toggling from light to dark theme is fairly simple, we just need to add a CSS variable that holds the background color black. In the dark mode, we will make the text color black and white in the light mode. For these minor adjustments, update the CSS variables which hold the text and change its colors. Here, we need to change the h1h3, and h4 text colors accordingly. We can see more functional results of the dark and light mode transition below.

The result will be responsive as well, so it will look good on all device sizes, from smartphones to desktops to large screens. Resize the browser to see the difference. The Bootstrap CDN (Content Delivery Network) is mainly used for responsiveness. One of the major advantages of using a CDN is you won’t need to download the libraries and host them yourself. You can extend it just by mentioning it in the head tag.

Now you know how to implement the Light/Dark mode feature from scratch. Whether you place your toggle switch on the navigation bar, footer, or anywhere in the webpage, make sure it stands out to the users. The users should be easily able to navigate to the option pretty quickly. One such location would place it on the right-hand side of the navigation bar.

Usually, it doesn’t take too much space, so you can squash it next to the options of the navigation bar. It is still a good place to start, even if you don’t end up using the exact colors (theme) produced. We can still end up fine-tuning the colors that were used above.

Using it or experimenting as it is to transform it into something new. Implementing the light/dark mode feature to your website is fairly simple, of course, and there is no limit on what you can do with the dark mode theme. By introducing the light class based on user needs, you can boost the webpage further. You can also be able to use local storage to preserve the style and status that the user used in the application.

Final Output 

Toggle Between Light Dark Mode3  
Toggle Between Light Dark Mode2

Source code 

If you enjoyed reading this Dark Mode Toggle Button post and have found it useful for you, then please give a share with your friends, and follow me to get updates on my upcoming posts. You can connect with me on Instagram.

if you have any confusion Regarding Dark Mode Toggle Button Comment below or you can contact us by filling out our contact us form from the home section.

written by – Ninja_webTech

Share on:

Leave a Comment