skip to Main Content

Note: not a duplicated because this is a custom made code and no other answer is answering my question, also because this is only javascript and not Jquery based

After reading hundreds of other posts and answers I decided to create a simple function instead of complicated/advanced ones, using just javascript. The problem is that I just started to learn javascript yesterday 🙂

What I want:

I want users to click on a single toggle button to turn dark mode on/off without complications in the code but just to save the value in localStorage and/or retrieve the chosen values from localStorage

The colors are just 2:

Dark mode is: body background #101010 and body font color if #FFFFFF

Light mode is: body background #FFFFFF and body font color if #101010

What I have

HTML

<button class="change" value="on">Dark mode is on</a>
<button class="change" value="off">Dark mode is off</a>
#would be nice with a single toggle button

Javascript

var document.querySelector(".change")
var body = document.getElementsByTagName("body")

btn.addEventListener("click", (e) => {
if (body[0].style.backgroundColor === "on") {
body[0].style.backgroundColor = "#101010"
body[0].style.color = "#FAFAFA"

} else {
body[0].style.backgroundColor = "#FAFAFA"
body[0].style.color = "#101010"

}
localStorage.setItem("bgColor", body[0].style.backgroundColor)
localStorage.setItem("textColor", body[0].style.color)
})
body[0].style.backgroundColor = localStorage.getItem("bgColor")
body[0].style.color = localStorage.getItem("textColor")

What I need

To make it save the chosen colors by the user and remember them with localstorage

To know if it is possible to make the button toggle with the text:
Dark mode is on/Dark mode is off

I created this Codepen with the code
https://codepen.io/familias/pen/gOQMrjX

2

Answers


  1. This should work fine now, I just added on to your code.

    The selected (mode)colors by the user will be saved in localStorage and retrieved when the page is loaded. Additionally I updated the CSS to include a .dark-mode class that applies the dark mode styles to the body element.

    html
    <button id="toggleBtn">Dark mode is on</button>
    

    javascript

    var toggleBtn = document.getElementById("toggleBtn");
    var body = document.getElementsByTagName("body")[0];
    
    toggleBtn.addEventListener("click", function() {
      var bgColor, textColor;
    
      if (body.classList.contains("dark-mode")) {
        body.classList.remove("dark-mode");
        toggleBtn.textContent = "Dark mode is on";
        bgColor = "#FFFFFF";
        textColor = "#101010";
      } else {
        body.classList.add("dark-mode");
        toggleBtn.textContent = "Dark mode is off";
        bgColor = "#101010";
        textColor = "#FFFFFF";
      }
    
      body.style.backgroundColor = bgColor;
      body.style.color = textColor;
    
      // Save the chosen colors to localStorage
      localStorage.setItem("bgColor", bgColor);
      localStorage.setItem("textColor", textColor);
    });
    
    // Retrieve saved colors from localStorage
    var savedBgColor = localStorage.getItem("bgColor");
    var savedTextColor = localStorage.getItem("textColor");
    
    if (savedBgColor && savedTextColor) {
      body.style.backgroundColor = savedBgColor;
      body.style.color = savedTextColor;
    
      if (savedBgColor === "#101010" && savedTextColor === "#FFFFFF") {
        body.classList.add("dark-mode");
        toggleBtn.textContent = "Dark mode is off";
      }
    }
    
    css
    body {
      margin: 0;
      height: 100%;
    }
    
    .dark-mode {
      background-color: #101010;
      color: #FFFFFF;
    }
    
    Login or Signup to reply.
  2. Newb here also, buy I’ll try to help you.

    I suggest using a checkbox. You can use CSS to make a slider button. Follow below what you need with my comments.

    window.addEventListener('DOMContentLoaded', function() {
        var checkbox = document.getElementById('change'); //Get the status os the checkbox
      
        checkbox.addEventListener('change', function() { //Checks if the status changed
          if (checkbox.checked) {
            document.body.classList.add('dark-theme'); //Uses the dark-theme that is in the CSS file.
            localStorage.setItem('theme', 'dark'); //Saves the "theme" in local storage
          } else {
            document.body.classList.remove('dark-theme'); //Goes back to normal model in the CSS file
            localStorage.setItem('theme', 'light');  //Saves the "theme" in local storage
          }
        });
      
        var savedTheme = localStorage.getItem('theme'); //When you load the page, it will check which 'theme' is stored. If it is normal, it does nothing, if it's dark, checks the checkbox and uses the dark-theme in CSS.
        if (savedTheme === 'dark') {
          checkbox.checked = true;
          document.body.classList.add('dark-theme');
        }
      });
    /* The switch - the box around the slider */
    .switch {
      position: relative;
      display: inline-block;
      width: 60px;
      height: 34px;
    }
    
    /* Hide default HTML checkbox */
    .switch input {
      opacity: 0;
      width: 0;
      height: 0;
    }
    
    /* The slider */
    .slider {
      position: absolute;
      cursor: pointer;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #ccc;
      -webkit-transition: .4s;
      transition: .4s;
    }
    
    .slider:before {
      position: absolute;
      content: "";
      height: 26px;
      width: 26px;
      left: 4px;
      bottom: 4px;
      background-color: white;
      -webkit-transition: .4s;
      transition: .4s;
    }
    
    input:checked + .slider {
      background-color: #2196F3;
    }
    
    input:focus + .slider {
      box-shadow: 0 0 1px #2196F3;
    }
    
    <!-- begin snippet: js hide: false console: true babel: false -->
    <label for="change">Dark mode</label>
    <label class="switch">
        <input type="checkbox" id="change">
        <span class="slider round"></span>
      </label>
    input:checked + .slider:before {
      -webkit-transform: translateX(26px);
      -ms-transform: translateX(26px);
      transform: translateX(26px);
    }
    
    /* Rounded sliders */
    .slider.round {
      border-radius: 34px;
    }
    
    .slider.round:before {
      border-radius: 50%;
    }
    
    <label class="switch">
      <input type="checkbox">
      <span class="slider round"></span>
    </label>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search