function darkMode() {
var element = document.body;
var content = document.getElementById("DarkModetext");
element.className = "darkmode11"
content.innerText = "Dark Mode is ON"
content.style.color = "white"
}
function lightMode() {
var element = document.body
var content = document.getElementById("DarkModetext")
content.innerText = "Dark Mode is OFF"
element.className = "lightmode11"
content.style.color = "black"
}
//I have made two function one is for darkmode and another is for light mode the problem is when i turn on the dark mode and refresh the page the dark mode get turned off
CodePudding user response:
You have to save mode setting somewhere like cookies or localStorage. Code below does this for you hope this is helpful. script type='module' means this script runs before page load so page doesnt flash white to black.
<script type="module">
if(localStorage.getItem('mode') == 'dark'){
darkmode();
}
function darkMode() {
localStorage.setItem("mode","dark");
var element = document.body;
var content = document.getElementById("DarkModetext");
element.className = "darkmode11"
content.innerText = "Dark Mode is ON"
content.style.color = "white"
}
function lightMode() {
localStorage.setItem("mode","light");
var element = document.body
var content = document.getElementById("DarkModetext")
content.innerText = "Dark Mode is OFF"
element.className = "lightmode11"
content.style.color = "black"
}
</script>
CodePudding user response:
You can easily store that dark mode is on or not in localStorage.
localStorage.setItem("theme", "dark");