Is there a way I can make a checkbox persist with the same state after switching to another page?

Viewed 37

I have actually tried doing this for hours on end but didn't get any result. What I want to do specifically is when the user changes to another page, I want dark mode or light mode(whichever they have chosen) to stay the same.

function changeMode() {
    if (document.getElementById("darkModeToggle").checked === true)
    {
        document.getElementById("dark").href = "Style.css";
        alert('You have turned on Dark Mode. Press Enter to continue.');
        localStorage.setItem("DarkMode", "on");
    }
    else{
        document.getElementById("dark").href = "lightmode2.css";
        alert('You have turned on Light Mode. Press Enter to continue.');
        localStorage.setItem("DarkMode", "off");
    }
}
<div id="darkMode">
    <input type="checkbox" class="tooltips" id="darkModeToggle" onchange=" changeMode();" autocomplete="on" checked>
</div>

I would like to have code of this in Javascript or CSS if possible, otherwise other languages are fine.

3 Answers

You can use local storage like the previous speakers

function changeMode() {
    if (document.getElementById("darkModeToggle").checked === true)
    {
        document.getElementById("dark").href = "Style.css";
        alert('You have turned on Dark Mode. Press Enter to continue.');
        localStorage.setItem("DarkMode", JSON.stringify(true));
    }
    else{
        document.getElementById("dark").href = "lightmode2.css";
        alert('You have turned on Light Mode. Press Enter to continue.');
        localStorage.setItem("DarkMode", JSON.stringify(false));
    }
}

in an script tag you can say:

<script type="text/javascript">
  var darkmode = localStorage.getItem("DarkMode");
  if(darkmode) {
    document.getElementById("darkModeToggle").checked = JSON.parse(darkmode) || false
  } else {
    // No DarkMode-Entry in localStorage
    document.getElementById("darkModeToggle").checked = false
  }

</script>

Just use localStorage to save selected theme mode and every time the page loads check the saved value if exists.

You are storing to localStorage but missing to retrieve it back and use it. You need to add following code on page load:

    let darkMode = localStorage.getItem("DarkMode");
    document.getElementById("darkModeToggle").checked = darkMode ? (darkMode == "on") : false;
Related