0

I have made a button and when it is clicked the colors of my website will change (which works fine). However, when a link is clicked or the page is refreshed it will not save the new css color values, it will just go back to how the page looks by default. Please let me know how I can save these values so it will not change on page refresh or when a tab is clicked. I appreciate any help you can give :)

Thank you!!

function toggleDarkLight(event) {
  var body = document.getElementById("body");
  var currentClass = body.className;
  body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
 }
<body id="body" class="light-mode">
<button type="button" name="dark_light" onclick="toggleDarkLight()" title="Toggle dark/light mode">dark</button></body>
J V
  • 123
  • 1
  • 5
  • 1
    Have you considered using SessionState or LocalStorage to save the state? – Rex Charles Sep 23 '19 at 21:07
  • Here is a stackoverflow answer that is similar and may be useful https://stackoverflow.com/questions/12895754/how-to-save-the-state-of-a-javascript-variable-that-is-used-in-multiple-html-pag – Rex Charles Sep 23 '19 at 21:17

1 Answers1

1

You should use localStorage

document.body.onload=function(){
        var mode = localStorage.getItem("mode")=="" ? mode="light-mode" :  mode=localStorage.getItem('mode');
        var body = document.getElementById("body");
        body.className = mode;
    }

    function toggleDarkLight(event) {
        var body = document.getElementById("body");
        var currentClass = body.className;
        body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
        localStorage.setItem("mode",body.className)
    }
Ves04
  • 71
  • 2
  • 5