Note: not a duplicated because this is a custom made code and no other answer is answering my question, also because this is only javascript and not Jquery based
After reading hundreds of other posts and answers I decided to create a simple function instead of complicated/advanced ones, using just javascript. The problem is that I just started to learn javascript yesterday 🙂
What I want:
I want users to click on a single toggle button to turn dark mode on/off without complications in the code but just to save the value in localStorage and/or retrieve the chosen values from localStorage
The colors are just 2:
Dark mode is: body background #101010 and body font color if #FFFFFF
Light mode is: body background #FFFFFF and body font color if #101010
What I have
HTML
<button class="change" value="on">Dark mode is on</a>
<button class="change" value="off">Dark mode is off</a>
#would be nice with a single toggle button
Javascript
var document.querySelector(".change")
var body = document.getElementsByTagName("body")
btn.addEventListener("click", (e) => {
if (body[0].style.backgroundColor === "on") {
body[0].style.backgroundColor = "#101010"
body[0].style.color = "#FAFAFA"
} else {
body[0].style.backgroundColor = "#FAFAFA"
body[0].style.color = "#101010"
}
localStorage.setItem("bgColor", body[0].style.backgroundColor)
localStorage.setItem("textColor", body[0].style.color)
})
body[0].style.backgroundColor = localStorage.getItem("bgColor")
body[0].style.color = localStorage.getItem("textColor")
What I need
To make it save the chosen colors by the user and remember them with localstorage
To know if it is possible to make the button toggle with the text:
Dark mode is on/Dark mode is off
I created this Codepen with the code
https://codepen.io/familias/pen/gOQMrjX
2
Answers
This should work fine now, I just added on to your code.
The selected (mode)colors by the user will be saved in localStorage and retrieved when the page is loaded. Additionally I updated the CSS to include a
.dark-mode
class that applies the dark mode styles to the body element.javascript
Newb here also, buy I’ll try to help you.
I suggest using a checkbox. You can use CSS to make a slider button. Follow below what you need with my comments.