Sovann Sun
Sovann Sun

Reputation: 21

Day Mode and Night Mode

I have tried to create the day mode and night with a check box button. it's working well. the default mode is day mode but the problem is when I'm in night mode then refresh the page or go to other pages on the site it will be back to day mode

JavaScript

const themeToggler = document.querySelector(".theme-toggler");

//Change Theme
themeToggler.addEventListener("click", () => {
  document.body.classList.toggle("dark-theme-variables");
  themeToggler.querySelector("span:nth-child(1)").classList.toggle("active");
  themeToggler.querySelector("span:nth-child(2)").classList.toggle("active");
});

Upvotes: 1

Views: 365

Answers (2)

Sovann Sun
Sovann Sun

Reputation: 21

You could try this

const themeToggler = document.querySelector(".theme-toggler");

//Change Theme
function darkmode() {
  let SetTheme = document.body;
  SetTheme.classList.toggle("dark-theme-variables");

  let theme;

  if (SetTheme.classList.contains("dark-theme-variables")) {
    console.log("Dark Mode");
    theme = "DARK";
  } else {
    console.log("Light Mode");
    theme = "LIGHT";
  }

  localStorage.setItem("PageTheme", JSON.stringify(theme));
}

let GetTheme = JSON.parse(localStorage.getItem("PageTheme"));
console.log(GetTheme);

if (GetTheme === "DARK") {
  document.body.classList = "dark-theme-variables";
}

Upvotes: 0

Marco
Marco

Reputation: 7271

This is expected behavior, state changes made via JavaScript are not preserved between site reloads.

You need some kind of mechanism, that'll store the preferred mode on the client's device.

As far I know there are two ways you can do this:

Example (from mdn) using LocalStorage:

// Stores "Tom" in "myCat"
localStorage.setItem("myCat", "Tom");

// Retrieves whatever is in "myCat":
const cat = localStorage.getItem("myCat");

Adjusted to your use case, you can do something like this:

const themeToggler = document.querySelector(".theme-toggler");

//Change Theme
themeToggler.addEventListener("click", () => {
  document.body.classList.toggle("dark-theme-variables");

  const is_dark_mode = document.body.classList.contains(
    "dark-theme-variables"
  )

  // storing the user's preference in LocalStorage
  window.localStorage.setItem("dark-mode", is_dark_mode)
});

Later you can retrieve the value and adjust the classes of <body>:

const wants_dark_mode = window.localStorage.getItem("dark-mode") === true

if (wants_dark_mode) {
  document.body.classList.add("dark-theme-variables")
}

Upvotes: 2

Related Questions