Hello sir I'm practicing my vanilla javascript. I am trying to create a "Hangman Game" when the correct letters are clicked from the buttons.. You win. I have all these buttons in queryselector(letterA to letterZ).
The problem using this function.. the winAlert = visible implements
when the letterS
was clicked (last letter of "cautious").
So is there a way when you clicked all the letters of cautious in any order the winAlert.style.visibility = "visible"
will be execute inside the function?
I've tried everything in the last hours.. buttons.forEach
, slice etc. nothing works.
function youWonCautious() {
var buttons = [letterC, letterA, letterT, letterI, letterU, letterI, letterO, letterS]
for (var i = 0; i < buttons.length; i ) {
var button = buttons[0, 1, 2, 3, 4, 5, 6, 7];
button.onclick = function() {
winAlert.style.visibility = "visible"
}
}
}
CodePudding user response:
Buttons don't automatically maintain any state about whether they were clicked. You can do this yourself using the dataset
property of the button.
Then your function can test whether all the buttons have this property set.
Or maybe you can change your buttons to checkboxes, and use the checked
property.
function allButtonsClicked(buttons) {
return buttons.every(b => b.dataset.chosen == 'true')
}
function youWonCautious() {
var buttons = [letterC, letterA, letterT, letterI, letterU, letterO, letterS];
buttons.forEach(button => {
button.dataset.chosen = 'true';
if (allButtonsClicked(buttons)) {
winAlert.style.visibility = "visible";
}
});
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can create a global array in which log the alphabets clicked by the user. check for the alphabets in the global array variable and answer array. If matches Pass alert message else fail message to user.