skip to Main Content

I’m trying to make a little site showcasing what I have made. However im not sure how to make sure my website remembers a users dark mode choice.

I have read other stack overflow questions where the answer was cookies or localStorage. Though i dont quite understand how to implement this sadly. Since im pretty new to javascript.

My dark mode is selected via a switch. When the switch is clicked the entire page will get a black background color and the text will change from black to white.

I have the dark mode switch working on all 3 sites. However i cant seem to make the website remember the users dark mode choice. So everytime the page is refreshed or the user clicks on a different nested site. The site reverts back to the default state which is white.

Every page has its own function since i need to highlight a paragraph in the header tag. To make sure the user knows what page they are on.

How do i save the dark mode input and read it across all the 3 nested sites so it doesnt reset when a new page is visited?

Any input is very much appreciated

Edit: I dont know if its worth mentioning. however the default colour for the website is white with black text. all dark mode does is change the color. though im not sure how to remember that user choice.

function toggleDarkMode1() {
  var element = document.body;
  element.classList.toggle("dark-mode");
  var test1 = document.getElementById("changeMe1");
  test1.classList.toggle("dark-mode");
  var test2 = document.getElementById("change2");
  test2.classList.toggle("dark-mode-header");
  var test3 = document.getElementById("changeMe3");
  test3.classList.toggle("dark-mode");
}
.dark-mode {
  background-color: black;
  color: white;
}

.dark-mode-header {
  background-color: black;
  color: white;
  border-bottom: none;
  border-bottom: 2px solid white;
}
<header>
  <a href="./resources/nestedPages/projectsPage/index.html" id="changeMe1">
    <p class="projectsHeader" id="change1">Projects</p>
  </a>
  <a href="./index.html" id="changeMe2">
    <p class="aboutMeHeader" id="change2">About me</p>
  </a>
  <a href="./resources/nestedPages/contactPage/index.html" id="changeMe3">
    <p class="contactHeader">Contact</p>
  </a>
</header>
<div class="DMDiv">
  <p>Dark mode</p>
  <label class="switch">
    <input type="checkbox" id="darkmode" onclick="toggleDarkMode1()">
    <span class="slider"></span>
  </label>
</div>

3

Answers


  1. Let’s create a single function that can be reused across your pages to handle dark mode toggling and persistence. Here’s the modified code:

    function toggleDarkMode() {
      var element = document.body;
      element.classList.toggle("dark-mode");
      document.getElementById("changeMe1").classList.toggle("dark-mode");
      document.getElementById("change2").classList.toggle("dark-mode-header");
      document.getElementById("changeMe3").classList.toggle("dark-mode");
    
      // Check if dark mode is enabled and save the preference in localStorage
      var darkModeEnabled = element.classList.contains("dark-mode");
      localStorage.setItem("darkMode", darkModeEnabled);
    }
    
    function applyDarkModePreference() {
      var darkModeEnabled = localStorage.getItem("darkMode") === "true";
      var element = document.body;
    
      // Apply dark mode preference
      if (darkModeEnabled) {
        element.classList.add("dark-mode");
        document.getElementById("changeMe1").classList.add("dark-mode");
        document.getElementById("change2").classList.add("dark-mode-header");
        document.getElementById("changeMe3").classList.add("dark-mode");
      }
    }
    
    // Call the applyDarkModePreference function when the page loads
    applyDarkModePreference();

    Now, you can use the toggleDarkMode function for the dark mode switch, and the applyDarkModePreference function to apply the user’s preference when the page loads. Include these functions in each of your pages, and they should work consistently across the site.

    Login or Signup to reply.
  2. To persist the user’s dark mode choice across different pages, you can use localStorage in JavaScript. Here’s a modified version of your toggleDarkMode1 function that saves the dark mode state in the local storage:

    function toggleDarkMode1() {
      var element = document.body;
      element.classList.toggle("dark-mode");
      var test1 = document.getElementById("changeMe1");
      test1.classList.toggle("dark-mode");
      var test2 = document.getElementById("change2");
      test2.classList.toggle("dark-mode-header");
      var test3 = document.getElementById("changeMe3");
      test3.classList.toggle("dark-mode");
    
      // Save dark mode state to localStorage
      var isDarkMode = element.classList.contains("dark-mode");
      localStorage.setItem("darkMode", isDarkMode);
    }
    
    // Check the initial dark mode state on page load
    function checkDarkMode() {
      var isDarkMode = localStorage.getItem("darkMode");
      var element = document.body;
      if (isDarkMode === "true") {
        element.classList.add("dark-mode");
      } else {
        element.classList.remove("dark-mode");
      }
    }
    
    // Call checkDarkMode on page load
    checkDarkMode();
    

    This modified code adds a call to localStorage.setItem to save the dark mode state whenever the user toggles the switch. It also includes a new function checkDarkMode that reads the dark mode state from localStorage on page load and applies the appropriate class to the body element.

    Make sure to call checkDarkMode() when each page is loaded to apply the correct initial dark mode state. You can place this call at the end of your script or within a DOMContentLoaded event listener.

    Login or Signup to reply.
  3. You could use cookies/local storage. You’d need to store the updated value whenever you change colour, and would need to check it on page load. I personally prefer localStorage so will be using that, but the concept is the same for cookies!

    The one thing I would do differently is adding a wrapper around toggleDarkMode so that we can reuse this code for changing the page colour on load, without it changing our stored value

    //check for value on page load
    let darkMode = localStorage.getItem("darkMode") == "true"; //returns stored value or null if not set
    
    if(darkMode){
      toggleDarkMode(); //I'm assuming your page starts in light mode, so a call to toggle should switch everything over!
    }
    
    //new wrapper function
    const updateDarkMode = () => {
      darkMode = !darkMode; //invert our variable
      localStorage.setItem("darkMode", darkMode); //save it in local storage
      toggleDarkMode(); //now update our styles!
    }
    

    The only other change you would need to make, is to reference the dark mode wrapper in your HTML

    <input type="checkbox" id="darkmode" onclick="updateDarkMode()">
    

    Edit: Another good thing to do would be to check if the user prefers light/dark mode, and you can set up your default state that way. We can do this using the window.matchMedia function, which would see your initial loading change to

    const getInitialState = () => {
      const initialValue = localStorage.getItem("darkMode");
    
      if(initialValue === null){
        return window.matchMedia('(prefers-color-scheme: dark)').matches;
      }
    
      return initialValue == "true";
    }
    
    let darkMode = getInitialState();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search