I'm trying to create a dark mode toggle button and everything went fine. Dark mode is working on my website but when I refresh a page, or go to other post, I should turn on the button again. Here's a Simplified code of what I'm using on my website, https://codepen.io/pen/?template=poyYapw. Also, myFunction1
is not working on my website, I don't know why. myFunction1
is working on codepen, w3schools etc but it's not working on my website. Can anyone provide me a javascript function which will solve both these issues.
Asked
Active
Viewed 63 times
-1
-
1you should store it on cookie or localStorage – Jerson Sep 30 '20 at 11:26
-
advice for how you build that up: Dont use several script tags, put both functions in the same one, also, the functions are pretty much activated with the same condition.. soo you dont need an click event for both of them, you can either activate myFunction1 inside the Toggledark-function or even just combine them into 1 single function. I don't see any need for there being 2 seperate functions with the same condition – Warden330 Sep 30 '20 at 11:29
-
Didn't really get what I needed. I mixed both functions but dark mode gets turned off when I reload a page or try to go onto post. Also, myFunction 1() us not working on my website but I don't know why. I'm beginner so can any one please provide me code. – Sep 30 '20 at 12:07
1 Answers
0
I'd recommend using localStorage.
You might not need to, but there's a way to detect dark mode: How do I detect dark mode using JavaScript?
If you use detection, save a boolean to localStorage that dark mode was detected.
The detection doesn't work here, but it should on your website.
var dark = localStorage.getItem("darkmode") || "false";
var detected = localStorage.getItem("dmodedetected") || "false";
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches & detected == "false") {
document.body.classList.add("darkmode");
}
detected = true;
localStorage.setItem("dmodedetected", "true");
function toggledmode() {
if (dark == "false") {
dark = "true";
document.body.classList.remove("darkmode");
}
else {
dark = "false";
document.body.classList.add("darkmode");
}
localStorage.setItem("darkmode", dark);
}
body {
background-color: white;
}
body.darkmode {
background-color: black;
}
<html>
<body>
<button onclick="toggledmode()">Toggle</button>
<script>
</script>
</body>
</html>

Axwabo
- 49
- 7