7. Respond to Answer Clicks

When a Player Clicks an Answer

The onClickedAnswer( ) function is called by the Trivia library when a button of class "answer-btn" is clicked. In the code below you will notice that a parameter, isCorrect, is "passed" to the function to indicate whether the answer is correct or not. Based on the answer we will provide appropriate feedback by inserting text and showing the "feedback" HTML element. We will also highlight the correct answer by adding a "highlight" class to the correct answer button. Finally, we will wait 3 seconds then use the trivia library method to gotoNextQuestion. Update your function to match the one below.

JavaScript
function onClickedAnswer(isCorrect) {
  if (isCorrect) $("#feedback").html(`Way to go!`).show();
  else $("#feedback").html(`Better luck next time.`).show();
  $("#correctAnswer").addClass("highlight"); //highlight right answer
  setTimeout(trivia.gotoNextQuestion, 3000); //wait 3 secs...next question
}

In order for the button highlight to work you need to add the following to your CSS. Add this to the bottom of your CSS.

CSS
.highlight {
  background-color: green;
  color: white;
}

If you run your trivia now the first question should respond nicely to a clicked answer, but you will notice a couple of problems once you get passed the first question. The highlight is stuck on and the feedback is not cleared. Let's fix that by adding two lines of code to your displayQuestion( ) function.

Add the code below just after $("#question-screen").show(); inside your displayQuestion( ) function. This resets your feedback.

JS
  $("#correctAnswer").removeClass("highlight");
  $("#feedback").hide();

Your trivia game should be clipping along well now. The final piece is to handle what happens when all questions have been answered.

Last updated