Saving a cookie for darkmode/lightmode JS - Issues

57 Views Asked by At

I am trying to make the cookie load when the body does, and then check what value it is. If darkmode = true, then it should display css/cssmain.css. If it is false, it should display css/csslight.css. The cookie works: If I use the button to switch from dark to light, it changes darkmode from true (dark) to light (false) and vice-versa. It even stays when I refresh the page, but the css switches to its default file.

Basically, I can not figure out how to make darkMode go into the if statement in my javascript. I tried it with onload="getCookie(darkMode)" to try and put the cookie darkMode's value (true or false) into the script. It seems to just not run the script, because even if I add an alert, the alert does not pop up when I use the button.

HTML:

<head>
    <title>Freshwater Fish</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="css/cssmain.css">
    <link rel="stylesheet" type="text/css" href="css/desktopview.css">
    <link rel="stylesheet" type="text/css" href="css/mobile.css">
    <link rel="stylesheet" type="text/css" href="css/slides.css">
    <link id='css_theme' rel='stylesheet' type='text/css' href='css/csslight.css'>
    <script src="js/fullstackfrog.js"></script>
</head>
<body onload="getCookie(darkMode)">

<button  class="lightmodeButton" onclick="document.getElementById('css_theme').setAttribute('href', document.getElementById('theme').value, document.cookie = 'darkMode=true'); if (document.getElementById('theme').value == 'css/cssmain.css'){  document.getElementById('theme').value = 'css/csslight.css'; document.cookie = 'darkMode=true';} else{ document.getElementById('theme').value = 'css/cssmain.css'; document.cookie = 'darkMode=false';}">Light/Dark</button>
<input type="hidden" id="theme" value="css/cssmain.css">

</body>
</html>

JS (fullstackfrog.js):

function getCookie(name) {
  if (name) {
    document.getElementById('theme').value = 'css/cssmain.css';
  }
  else {
    document.getElementById('theme').value = 'css/csslight.css';
  }
}
1

There are 1 best solutions below

2
user1280483 On

Do you know how cookies work? document.cookie will just stay the same. You need to write something to get the cookie and parse the value from document.cookie. Try reading https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie and use the examples.