Search code examples
javascriptdom-eventsdarkmode

Javascript dark mode toggle not working with onClick


main.js:

   function darkModeToggle() {
    var element = document.body;
    element.classList.add("darkmode");
    localStorage.setItem("mode", "dark");
    let mode = localStorage.getItem('mode')

    if (mode === 'dark') {
        document.getElementById("darkmode-button").onclick = lightModeToggle();
        document.getElementById("darkmode-button").innerHTML = 'Light mode';
        localStorage.setItem("mode", "light");
        return false
    }

}


function lightModeToggle() {
    var element = document.body;
    element.classList.remove("darkmode");
    localStorage.setItem("mode", "light");

    let mode = localStorage.getItem('mode')
    console.log('Hello')

    if (mode === 'light') {
        localStorage.setItem("mode", "dark");

        document.getElementById("darkmode-button").onclick = darkModeToggle();
        document.getElementById("darkmode-button").innerHTML = 'Dark mode'
    }

}

I have a button in home.html

<button onClick='darkModeToggle' id='darkmode-button'>Dark mode</button>

But this does not work.. I want to store the settings of the user if they want dark mode or light mode in the website..

Why does my current code not work and how to fix it?


Solution

  • You can put this all in one function. There is no need for two functions. Add a default class for example light to your body and then change it when clicking the button. So by default light is display if the user doesn't set a preference.

    Using localStorage has the advantage that the user preference will be stored next time the user visits your site.

    When clicking the button read the localStorage. If no value has been set yet, set it to the opposite of the default one.

       window.onload = function() {
         setMode();
       };
        
       function setMode() {
         let mode = localStorage.getItem('mode');
         if(!mode) mode = 'light';
         document.body.classList.add(mode);
       }
    
       function toggleMode() {
        let element = document.body;
        let btn = document.getElementById("darkmode-button");
        let mode = localStorage.getItem('mode')
                
        if(!mode) mode = 'dark';
    
        if(mode == 'dark') {
           localStorage.setItem("mode", "light");
           element.classList.remove("dark");
           element.classList.add("light");
           btn.innerHTML = 'Dark mode';
           
        }
        else {
          localStorage.setItem("mode", "dark");
          element.classList.remove("light");
          element.classList.add("dark");
          btn.innerHTML = 'Light mode';
        }    
    }
    body.light {
      background: #fff;
    }
    
    body.dark {
      background: #555;
    }
    <body class="light">
      <button onclick='toggleMode()' id='darkmode-button'>Dark mode</button>
    </body>