0

I have this simple code to turn a webpage into dark/light mode. It works fine on the page you are, but if I click any links or buttons to redirect me from index.html to test.html for example, then the settings resets to default. Let's say I want to browse my page in light mode, and lick test button it goes back to dark mode. How do I make it remember to stay in the same mode I choose? Here is what I got.

Index.html

<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Dark -Light Mode Switcher</title>
<link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<body id="body" class="dark-mode">
<h1>Dark/Light Mode Switcher</h1>

<button type="button" name="dark_light" onclick="toggleDarkLight()" title="Toggle dark/light mode">🌛 
</button>

<p><a href="test.html"><button name="test">TEST PAGE</font></button></a>

<!-- partial -->
<script  src="./script.js"></script>

</body>
</html>

Script.js

function toggleDarkLight() {
var body = document.getElementById("body");
var currentClass = body.className;
body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
}

Style.css

body.dark-mode {
background-color: #111;
color: #eee;
}
body.dark-mode a {
color: #111;
}
body.dark-mode button {
background-color: #eee;
color: #111;
}

body.light-mode {
background-color: #eee;
color: #111;
}
body.light-mode a {
color: #111;
}
body.light-mode button {
background-color: #111;
color: #eee;
}
2
  • 1
    Read the following: css-tricks.com/dark-modes-with-css Commented Dec 8, 2019 at 2:39
  • You might want to think about using something like cookies OR local storage for this. This way you can check the value set while navigating on your domain to set the correct theme. Commented Dec 8, 2019 at 3:44

1 Answer 1

1

If you update your Script.js like below, you will obtain what you want :

body.className=localStorage.getItem("stateMode");
function toggleDarkLight() {
var body = document.getElementById("body");
var currentClass = body.className;
body.className = currentClass == "dark-mode" ? "light-mode" : "dark-mode";
localStorage.setItem("stateMode",body.className);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is excellent, and works exactly as needed. Thank you for your time and help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.