user15490220
user15490220

Reputation:

Saving a cookie for darkmode/lightmode JS - Issues

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';
  }
}

Upvotes: 0

Views: 49

Answers (1)

user1280483
user1280483

Reputation: 560

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.

Upvotes: 0

Related Questions