Im trying to make it when buttons are clicked it causes a function which returns it to true and when it returns to true another button checks that and causes another function to run.
WHAT I TRIED:
function done1(){
return true;
}
function done2(){
return true;
}
var done1=done1();
var done2=done2();
function done3(){
if ( done1 && done2){
alert('hello');
}
}
<button id="1" onclick="done1(); ">1</button>
<button id="2" onclick="done2()">2</button>
<button id="3" onclick="done3()">3</button>
When i press the 3rd button it still shows the alert even when the buttons are not clicked. Its supposed to make it return true when the buttons are clicked but it does it even if its not clicked.
CodePudding user response:
What you need is instead of returning a value from each function, change value of a variable. For example, something like this:
const trigger = [0, 0];
function done1()
{
trigger[0] = 1;
}
function done2()
{
trigger[1] = 1;
}
function done3(){
if ( trigger[0] trigger[1] == 2){
alert('hello');
}
}
<button id="1" onclick="done1()">1</button>
<button id="2" onclick="done2()">2</button>
<button id="3" onclick="done3()">3</button>
Or if you want be able toggle button's state (aka second press will undo) you could store values of each button as bits (up to 32 buttons) with something like this:
let trigger = 0;
function done(val)
{
if (!val && trigger == 7)
alert('hello');
else
trigger = trigger ^ val; //binary XOR
}
<button id="1" onclick="done(1)">1</button>
<button id="2" onclick="done(2)">2</button>
<button id="3" onclick="done(4)">3</button>
<button id="4" onclick="done()">4</button>