javascripthtmlcsslocal-storagedarkmode

Remembering dark mode between pages in local storage


I have this script toggle dark mode specified in my css but can't figure out how to make the dark mode stay on between pages.

Thanks ahead!

html:

    <img onclick="darkmode()" id="darktoggledesktop" src="media/darktoggle.svg" alt="">
    <script>
        function darkmode() {
          var element = document.body;
          element.classList.toggle("dark-mode");
        }
    </script>
    <script>
        function menufunction() {
          var x = document.getElementById("mobilemenuopen");
          if (x.style.display === "block") {
            x.style.display = "none";
          } else {
            x.style.display = "block";
          }
        }
        </script>

css:

.dark-mode {
    background-color: black;
    color: white;
    transition: 0.4s;
  }

I tried following similar threads here but can't seem to get this work.


Solution

  • As you mentioned you can do this using the localStorage. If you don't know how to use it you can read more about it here.

    For this specific example, here's a working dark switch toggle script, which uses the localStorage to store a user's preference on page load.

    <img onclick="toggleDarkMode()" id="darktoggledesktop" src="media/darktoggle.svg" alt="">
    <script>
        // Function to toggle dark mode and save preference in localStorage
        function toggleDarkMode() {
            let element = document.body;
            element.classList.toggle("dark-mode");
            if (element.classList.contains("dark-mode")) {
                localStorage.setItem("darkMode", "enabled");
            } else {
                localStorage.setItem("darkMode", "disabled");
            }
        }
    
        // Function to load dark mode preference on page load
        function loadDarkModePreference() {
            let darkMode = localStorage.getItem("darkMode");
            if (darkMode === "enabled") {
                document.body.classList.add("dark-mode");
            }
        }
    
        // Load dark mode preference when the page loads
        window.onload = loadDarkModePreference;
    </script>
    <script>
        function menufunction() {
            let x = document.getElementById("mobilemenuopen");
            if (x.style.display === "block") {
                x.style.display = "none";
            } else {
                x.style.display = "block";
            }
        }
    </script>