Search code examples
javascripthtmlcssthemesdarkmode

how to Change dark theme to light teme after reclick


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 ?


Solution

  • 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"/>