Search code examples
javascripthtmlcsscheckboxonchange

Content of the page back to normal (as it was before) when the checkbox input is unchecked


SO I wanted to change few contents of the page when the checkbox input is checked and bring everything back to it was before when the checkbox is unchecked.

    <div class="switch">
        <input type="checkbox" name="checkbox" id="checkbox" onchange="darkmode(this)" />
    </div>

    <section id="section">
    <p>This is a line</p>
    </section>
    <script>
        function darkmode(checkboxElem) {
          if (checkboxElem.checked) {
            document.body.style.backgroundColor = "black";
            document.getElementById("checkbox").style.borderColor = "white";
            document.getElementById("section").style.color ="white"; 
          }else {
            document.body.style.backgroundColor = "white";
            document.getElementById("checkbox").style.borderColor = "black";
            document.getElementById("section").style.color ="black"; 
          }
        }   
    </script>

I figured I can do that by giving value to every content that was changed. In the 'else' statement I will have to give every content it's the value of 'as it was before' Doing this will take a lot of time and I will have to write everything twice (in CSS and Javascript).

If there is a way to bring everything to default when the checkbox is unchecked without without giving every element their pervious value. Please, let me know.

Thank you


Solution

  • Easiest solution would be to add and remove a class to the body as in the snippet below. Then you delcare all styling for the darkmode within the css. Its important, that it is written at the bottom of the normal css.

    function darkmode(checkboxElem) {
      var darkMode = document.body;
      if (checkboxElem.checked) {
        darkMode.classList.add("dark-mode");
      } else {
        darkMode.classList.remove("dark-mode");
      }
    }
    .dark-mode {
      color: white;
      background-color: black;
    }
    <body>
      <div class="switch">
        <input type="checkbox" name="checkbox" id="checkbox" onchange="darkmode(this)" />
      </div>
    
      <section id="section">
        <p>This is a line</p>
      </section>
    </body>