I'm trying to make a webpage that when you click on both buttons it'll change the background color, but for some reason that event won't happen unless i change them from the original variable. I think it's because my functions aren't getting and changing my variable's value for some reason but there may be another reason that i can't see. Is there a correct way to change variable values inside functions that i'm not using?
let uno = false;
let dos = false;
function change1() {
uno = true;
return uno;
}
function change2() {
dos = true;
return dos;
}
if (uno && dos) {
document.body.classList.add("change");
}
html,
body {
height: 100%;
width: 100%;
}
body {
margin: 0;
background-color: #8AB0AB;
display: flex;
align-items: center;
justify-content: center;
}
.change {
background-color: #F4D35E;
}
<html>
<body>
<button id="1" onclick="change1()">
#1
</button>
<button id='2' onclick="change2()">
#2
</button>
</body>
</html>
CodePudding user response:
You're only checking the boolean variables once, when the page first loads, not after the clicks change the values of the variables.
You need to run the if (uno && dos)
code after every click on one of the buttons, to update the body class.
There's no need for the return
statements in the functions, since the return value of onXXX()
functions isn't used.
let uno = false;
let dos = false;
function change1() {
uno = true;
change_body();
}
function change2() {
dos = true;
change_body();
}
function change_body() {
if (uno && dos) {
document.body.classList.add("change");
}
}
html,
body {
height: 100%;
width: 100%;
}
body {
margin: 0;
background-color: #8AB0AB;
display: flex;
align-items: center;
justify-content: center;
}
.change {
background-color: #F4D35E;
}
<html>
<body>
<button id="1" onclick="change1()">
#1
</button>
<button id='2' onclick="change2()">
#2
</button>
</body>
</html>
CodePudding user response:
You need to evaluate the state after the button is clicked. Something like:
var buttons = document.getElementsByTagName("button");
var isOn = true;
if(buttons){
for (var i = 0; i < buttons.length; i ) {
buttons[i].addEventListener("click", function (evt) {
this.classList.toggle("highlight");
evaluateButtons();
});
}
}
function evaluateButtons(){
isOn = true;
for (var i = 0; i < buttons.length; i ) {
if(!buttons[i].classList.contains("highlight")){
isOn = false;
}
}
if (isOn){
document.body.classList.add("modified");
} else {
document.body.classList.remove("modified");
}
}
.highlight{
background-color: green;
}
.modified{
background-color: gray;
}
<body>
<button>
#1
</button>
<button>
#2
</button>
</body>