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 ?
4
Answers
Don’t manipulate styles manually. Just toggle a class for
body
and write appropriate styles for this class:Base on your code :
Just make use of
toggle
classList and then use CSS to add your styles.Based on your current code, you can use a variable to keep track of the current theme state.
The initial state is assumed to be the light theme. Each time the button is clicked, it checks the current theme state. If it’s true, the light theme is applied; otherwise, the dark theme is applied. The flag variable is then toggled to switch the theme for the next click.