How can I get an alert when I click the third button having clicked the first two buttons first?

HTML

<button id="BtnOne" class="myBtns"></button>
<button id="BtnTwo" class="myBtns"></button>
<button id="BtnThree" class="myBtns"></button>

CSS

#divOne {
width: 200px;
height: 200px;
margin: 10px;
background-color: lightgreen;
}
.myBtns {
background-color: rebeccapurple;
width: 250px;
height: 250px;
margin: 20px;
}

JS

document.getElementById("BtnOne").addEventListener("click", showAlert);
document.getElementById("BtnTwo").addEventListener("click", showAlert);
document.getElementById("BtnThree").addEventListener("click", showAlert);
function showAlert() {
if (BtnOne.clicked == true && BtnTwo.clicked == true && BtnThree.clicked == true) {
alert("hello");
    }
};

CODEPEN
CODEPEN LINK

Hi,

You can set a clicked boolean for the two first buttons when they are clicked.
Then, when you click on the third button, you verify if the two booleans are true.

let btnOneClicked = false, btnTwoClicked = false;

document.getElementById("BtnOne").addEventListener("click", () => btnOneClicked = true);
document.getElementById("BtnTwo").addEventListener("click", () => btnTwoClicked = true);
document.getElementById("BtnThree").addEventListener("click", showAlert);

function showAlert() {
    if (btnOneClicked && btnTwoClicked) {
            alert("hello");
    }
};
    

thanks a lot super handy

1 Like