I know I’m a little late to the game, but I’m updating a trivia game that uses buttons.
This is how I am going about doing it →
HTML
<div id="quiz" class="displayMessage" data-username="">
<div class="triviaContainer" data-records=" ">
<div id="mainGame">
<div id="current">Current question is <span id="currentQuestion" data-record=""></span></div>
<div id="triviaSection" data-correct="">
<div id="questionBox">
<h2 id="question"></h2>
<button class="buttonStyle" id="ans1"></button>
<button class="buttonStyle" id="ans2"></button>
<button class="buttonStyle" id="ans3"></button>
<button class="buttonStyle" id="ans4"></button>
</div>
<div id="buttonContainer"></div>
</div>
<div id="headerStyle" data-user="">
<button id="next" class="nextBtn">Next</button>
<p id="score">Points: 0</p>
<p id="percent">100% Correct</p>
</div>
</div>
</div>
</div>
Setting up the buttons in Vanilla JavaScript →
/* Answer Buttons */
let answer1 = document.querySelector('#ans1');
let answer2 = document.querySelector('#ans2');
let answer3 = document.querySelector('#ans3');
let answer4 = document.querySelector('#ans4');
Setting up the buttons to display the questions →
/* Display the questions and answers on the page */
q["textContent"] = question;
answer1["textContent"] = ans1;
answer2["textContent"] = ans2;
answer3["textContent"] = ans3;
answer4["textContent"] = ans4;
/* Add Listener to Answer 1 */
answer1.addEventListener('click', pick1,false);
/* Add Listener to Answer 2 */
answer2.addEventListener('click', pick2,false);
/* There doesn't have to be 3 or 4 answers in the Trivia Game */
if (ans3 !== "") {
/* Add Listener to Answer 3 */
answer3.addEventListener('click', pick3,false);
}
if (ans4 !== "") {
/* Add Listener to Answer 4 */
answer4.addEventListener('click', pick4,false);
}
the functions for the addEventListeners →
/* All the data has been retrieved from the database table with exception to the correct answer and
* and in my opinion makes it doing this way cleaner when using add event listeners. That way removing the
* addEventListener is easier.
*/
const pick1 = () => {
let id = document.querySelector('#currentQuestion').getAttribute('data-record');
choice = 1;
retrieveAnswer(id);
}
const pick2 = () => {
let id = document.querySelector('#currentQuestion').getAttribute('data-record');
choice = 2;
retrieveAnswer(id);
}
const pick3 = () => {
let id = document.querySelector('#currentQuestion').getAttribute('data-record');
choice = 3;
retrieveAnswer(id);
}
const pick4 = () => {
let id = document.querySelector('#currentQuestion').getAttribute('data-record');
choice = 4;
retrieveAnswer(id);
}
I won’t bore you with the rest, but maybe this will help? This was done in Vanilla JavaScript
Here’s a very rough beta version of the game - https://www.fanoflego.com/trivia.php
Full JavaScript Code can be found here → fanoflego/trivia.js at main · Strider64/fanoflego · GitHub