Home > OS >  How to build a dark and light mode in html using different pages with codes?
How to build a dark and light mode in html using different pages with codes?

Time:10-19

I'm currently working on a website trying to build a settings page for the style of the website but I'm trying to use a different page with .css and .js so it doesn't just apply to one page it applies to all of the pages on the website.

Can someone work this out for me? This is my current. CSS.css (for my CSS) page & JS.js (for my JavaScript) page.

const toggle = document.getElementById("toggle");
const refresh = document.getElementById("refresh");
const theme = window.localStorage.getItem("theme");

/* verifica se o tema armazenado no localStorage é escuro
se sim aplica o tema escuro ao body */
if (theme === "dark") document.body.classList.add("dark");

// event listener para quando o botão de alterar o tema for clicado
toggle.addEventListener("click", () => {
  document.body.classList.toggle("dark");
  if (theme === "dark") {
    window.localStorage.setItem("theme", "light");
  } else window.localStorage.setItem("theme", "dark");
});

refresh.addEventListener("click", () => {
  window.location.reload();
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
/* Definição das cores */
body {
  /* cores de texto */
  --text-white: #ffffff;
  --text-dark: #142136;

  /* cores de fundo */
  --bg-grey-light: #f5f5f5;
  --bg-white: #ffffff;
  --bg-blue-dark: #142136;
  --bg-indigo: #6366f1;

  font-family: "Inter", sans-serif;
  line-height: 1.7;
  background-color: var(--bg-grey-light);
}
.dark {
  --text-white: #e6e6e6;
  --text-dark: #ffffff;
  --bg-grey-light: #142136;
  --bg-white: #22395d;
  --bg-blue-dark: #142136;
  --bg-indigo: #7577e1;
}
.container {
  max-width: 600px;
  margin: 40px auto;
  display: flex;
  padding: 20px;
  flex-direction: column;
}
.text-wrapper {
  width: 100%;
  padding: 20px;
  background-color: var(--bg-white);
  margin-bottom: 40px;
  border-radius: 10px;
}
.paragraph {
  font-size: 16px;
  color: var(--text-dark);
}
.heading {
  font-size: 40px;
  letter-spacing: 1px;
  font-weight: 900;
  margin-bottom: 40px;
  color: var(--text-dark);
}
.buttons {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 40px;
}
.button {
  width: 200px;
  padding: 5px;
  height: 40px;
  border: none;
  border-radius: 10px;
  font-family: inherit;
  cursor: pointer;
  background-color: var(--bg-indigo);
  color: var(--text-white);
  font-size: 16px;
  font-weight: 400;
  text-transform: capitalize;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
    <title>Dark mode Tutorial</title>
  </head>
  <body>
    <div >
      <h1 >
        Dark/Light theme switcher with HTML, CSS & Javascript Only
      </h1>
      <div >
        <!-- botão para fazer a troca de estados dark/light -->
        <button id="toggle" >toggle</button>
        <!-- botão para atualizar a página -->
        <button id="refresh" >refresh</button>
      </div>
      <div >
        <p >
          The United States shall be President of the States now existing shall
          think proper to admit, shall not be questioned in any Department or
          executed, and shall Commission all the Persons voted for, and
          Conviction of, Treason, Bribery, or other Property belonging to the
          which he was elected, be appointed to any civil Office under the
          United States, at the time of the State Legislature.
        </p>
      </div>
      <div >
        <p >
          Why, there's hardly enough of me left to make ONE respectable person!'
          Soon her eye fell on a little glass box that was lying on the top of
          her head though the doorway; `and even if I fell off the top of the
          house!' (Which was very likely it can talk: at any rate, there's no
          half afraid that it was only a mouse that had slipped in like herself.
          `As wet as ever,' said Alice in a great hurry to change the subject of
          must go by the carrier,' she thought; `and how funny it'll seem to dry
          and she ran with all her knowledge of history, Alice had not a VERY
          good opportunity for showing off her knowledge, as there was no `One,
          two, three, and away,' but they began running when they liked, so that
          it was too slippery; and when Alice had been all the way I want to go!
        </p>
      </div>
    </div>
    <script src="script.js"></script>
  </body>
</html>

CodePudding user response:

You'll need to put in storage not just a single toggled state (a theme of light or dark), but such a state for every single page. Use the pathname as the key.

// Set the theme from storage on pageload:
if (!localStorage.darkThemesByPage) {
  localStorage.darkThemesByPage = '{}';
}
const darkThemesByPage = JSON.parse(localStorage.darkThemesByPage);
const { pathname } = window.location;
if (darkThemesByPage[pathname]) {
  document.body.classList.add("dark");
}

// Change the state in storage when the user wants to change theme:
const toggleDarkThemeForPage = () => {
  // Retrieve storage again to preserve changes made on other pages
  // after this page was loaded
  const darkThemesByPage = JSON.parse(localStorage.darkThemesByPage);
  darkThemesByPage[pathname] = !darkThemesByPage[pathname];
  localStorage.darkThemesByPage = JSON.stringify(darkThemesByPage);
  // Apply the new state of the theme after being toggled:
  document.body.classList.toggle("dark", darkThemesByPage[pathname]);
};

Then just call toggleDarkThemeForPage when you need to toggle it, for example:

toggle.addEventListener("click", toggleDarkThemeForPage);

I'm using a boolean for the object values in storage above because it'll make toggling between light and dark easier - you just need to invert the truthyness of whatever the current state is. Then doing

document.body.classList.toggle("dark", darkThemesByPage[pathname]);

will apply the dark class if the value is true, and it'll remove the class otherwise.

  • Related