The reason is simple: You don't have proper code to switch back. It should look more like this (not tested):
var currentState = true;
function switchTheme() {
if (currentState) {
document.getElementById('css_file').href = "css/green-theme.css";
}
else{
document.getElementById('css_file').href = "css/style.css";
}
currentState = !currentState;
}
let changeButton = document.querySelector(".change_theme");
changeButton.addEventListener('click', switchTheme);
The problem is that you always set it to the normal theme and then back to the green theme which makes no sense to do because that changes nothing. What you want to do is save if you currently use the normal theme, if that's the case, then you enable the green theme, otherwise the normal one. currentState = !currentState means that you set current state to its opposite value, so true if it was false and false if it was true.
What your old code did was this:
function switchTheme() { //Button was pressed
let css = document.getElementById('css_file').href = "css/style.css";//Set the
//current theme to the normal one. Because it's css = href = "style", you set css to "style" (I think, or maybe just true because it's a valid operation, so don't quote me on that)
if (css) { //If css contains something true, this code is executed.
//Note that css is always "[...]style", so it's always a non-empty string which is true
return document.getElementById('css_file').href = "css/green-theme.css"; //Then set the style to green - this always happens so you can essentially delete every other line and nothing would change.
}
}
element. setAttribute('href', url)cssvariable to"css/style.css", and then doif ("css/style.css"), which is always true because a non-empty String is always truthy