Display Questions to Players
Learn how to display a trivia question to all players.
Task 11: Display a trivia question for all players
Next, when any of the players click on the “Get Question” button, the game should begin for all players in the room. The same trivia question should display in the “Trivia” section for all players. In the client, public/js/trivia.js, send an event called getQuestion to the server when any player clicks the “Get Question” button:
- In the client (i.e.,
public/js/trivia.js
), send an event calledgetQuestion
to the server when any player clicks on the “Get Question” button:
Press + to interact
const triviaQuestionButton = document.querySelector(".trivia__question-btn");triviaQuestionButton.addEventListener("click", () => {// pass null as the second argument because we're not sending any data to the server// alert the error if the server sends back an errorsocket.emit("getQuestion", null, (error) => {if (error) return alert(error);});});
We’ll use trivia questions from the Open Trivia Database API. Here’s an example of a JSON response from the API.
As the players interact with the game, we have to keep track of different pieces of data. This includes storing the current question prompt and correct answer, as well as keeping track of how many answers have been submitted.
- Let’s create helper