Currently, I'm tackling a quiz project that was assigned to me during my bootcamp. My focus right now is on the checkAnswer function, which evaluates the answer selected by the player.
const startButton = document.querySelector(".start") as HTMLButtonElement;
startButton.addEventListener("click", () => {
const presentation = document.querySelector(
".presentation"
) as HTMLDivElement;
presentation.style.display = "none";
questionContainer.style.display = "flex";
displayQuestion(questions[currentQuestion]);
console.log("je marche");
checkAnswer(questions[currentQuestion].correctAnswer);
});
function checkAnswer(correctAnswer: string) {
buttonListener(button1, correctAnswer);
buttonListener(button2, correctAnswer);
buttonListener(button3, correctAnswer);
buttonListener(button4, correctAnswer);
}
function buttonListener(button: HTMLButtonElement, correctAnswer: string) {
button.addEventListener("click", () => {
if (button.textContent === correctAnswer) {
console.log(`${button.textContent} is the right answer`);
score += 10;
currentQuestion++;
button.textContent = "";
console.log(
`The current score is ${score} and the next question is number ${
currentQuestion + 1
}`
);
displayQuestion(questions[currentQuestion]);
console.log(currentQuestion);
} else if (button.textContent !== correctAnswer) {
console.log(`${button.textContent} is not the right answer`);
score -= 5;
currentQuestion++;
button.textContent = "";
console.log(
`The current score is ${score} and the next question is number ${
currentQuestion + 1
}`
);
displayQuestion(questions[currentQuestion]);
console.log(currentQuestion);
}
});
}
Take a look at my repository for the complete code
Current Challenge:
- Upon selecting an answer, the display of the subsequent question occurs automatically, which aligns with the intended behavior.
- However, after answering the first question, the comparison made by the function registers incorrectly when moving to the second question. This discrepancy persists across all subsequent questions.
Potential Issue: The constant value of the correct answer remains unchanged between each question, causing the function to mistakenly evaluate the user's selection against the initial correct answer. This observation is corroborated by adjusting one of the answers in the second question to match the correct answer from the first question, resulting in the correct evaluation.
Attempted Solutions: I experimented with altering the correct answer by introducing a variable within the displayQuestion function, but this approach proved unsuccessful. Similarly, implementing a similar modification within the checkAnswer function did not yield the desired outcome.
I am seeking guidance to address this challenge without requesting a direct solution, aiming to regain my footing in resolving this issue.
Thank you for considering my inquiry!