Nvz_v1
Nvz_v1

Reputation: 21

How to store user choice across multiple sessions with JS?

I have two simple CSS sheets:

I have a button that calls a function onClick to toggle between the two sheets. I'm currently writing a code to store the user choice in a cookie (or local storage), but I'm not sure how to go about it.

function setTheme() {
    let theme = document.getElementsByTagName('link')[0];
    if (theme.getAttribute('href') == 'default.css') {
        theme.setAttribute('href', 'darkmode.css');
    } else {
        theme.setAttribute('href', 'default.css');
    }
}

I have tried adding a localStorage set to the end of that code but it just wouldn't work. I'd like to stay away from jQuery for this and stick to Javascript. I also want this to stay persistent across multiple sessions regardless of the browser being closed.

Upvotes: 2

Views: 251

Answers (1)

Buntel
Buntel

Reputation: 622

document.getElementById('theme').addEventListener('change', setTheme)

function applyTheme() {
  const theme = localStorage.getItem('theme')
  if (theme) {
    const link = document.getElementsByTagName('link')[0]
    link.setAttribute('href', theme)
  }
}

function setTheme(event) {
  localStorage.setItem('theme', event.target.value)
  applyTheme()
}
<link rel="stylesheet" href="default.css">
<select name="theme" id="theme">
  <option value="default.css">default</option>
  <option value="drak.css">dark</option>
</select>

Are trying to do something like this?

Upvotes: 2

Related Questions