how to Change dark theme to light teme after reclick

71 Views Asked by At

i made a button that when u click it, the webpage turn to dark theme but when i reclick it, it stays black i want it to return back to the default (white) like a loop

const myBtn = document.getElementById("darktheme");
const body = document.body;
const welcome = document.getElementById("txtt")

myBtn.addEventListener("click", function(){
    body.style.backgroundColor = "rgb(17, 17, 17)";
    body.style.color = "white";
    welcome.style.color = "white";
    
}) 

can anyone Help ?

3

There are 3 best solutions below

3
Mostafa Sabeghi On BEST ANSWER

Base on your code :

const myBtn = document.getElementById("darktheme");
const body = document.body;
const welcome = document.getElementById("txtt");

myBtn.addEventListener("click", function(){
    if(body.style.backgroundColor==="rgb(17, 17, 17)")
    {
      body.style.backgroundColor = "rgb(256, 256, 256)";
      body.style.color = "black";
      welcome.style.color = "black";
    }
    else
    {
      body.style.backgroundColor = "rgb(17, 17, 17)";
      body.style.color = "white";
      welcome.style.color = "black";
    }
}) 
<button id="darktheme">darktheme</button>
<input type="text" id="txtt"/>

4
Alexander Nenashev On

Don't manipulate styles manually. Just toggle a class for body and write appropriate styles for this class:

body.darktheme{
  color:white;
  background: #444;
}
<button onclick="document.body.classList.toggle('darktheme')">Toggle dark theme</button>

<h1>Hello World!</h1>

0
Mihai T On

Just make use of toggle classList and then use CSS to add your styles.

const myBtn = document.getElementById("toggle-theme");
const body = document.body;
const welcome = document.getElementById("txtt")

myBtn.addEventListener("click", function(){
   body.classList.toggle('dark')
    
}) 
body { background-color: white; color: black;}
body #txtt { color: black; }
body.dark { background-color:black; color: white}
body.dark #txtt { color: white }
<button id="toggle-theme">toggle</button>
<div id="txtt">Welcome</div>