Instead of constantly adding new click handlers without removing the old ones, a more efficient approach would be to treat questions and answers as data instead of code. By defining a structured data format that includes all questions, answers, and correct responses, you can avoid unnecessary repetition.
For example, create an array like this:
var questions = [{
question: "What is the best selling car of all time?",
answers: ["Toyota Camry", "Ford F-150", "Honda Civic", "Toyota Corolla"],
correct: 3 // note: first answer has index 0
}, {
question: "First introduced in 1974, which iconic hatchback still remains popular today?",
answers: ["Ford Mustang", "Volkswagen Golf", "Toyota Celica", "Fiat 500"],
correct: 1
}, {
question: "What is the world's fastest production car as of July 2020?",
answers: ["Koenigsegg Agera RS", "Hennessy Venom GT", "Buggatti Chiron Super Sport", "Lamborghini Aventador"],
correct: 2
}, {
question: "What 70s car is known for its suicide doors and convertible top?",
answers: ["Lincoln Continental", "Buick Rivera", "Ford Thunderbird", "Oldsmobile Toronado"],
correct: 0
}];
With this structure in place, all you need to do is iterate through the array from one question to the next by incrementing the index.
It's also recommended to give users some time to see the outcome of their answers before moving on to the next question. Displaying a new question with a "Correct" message before the user has responded can be confusing.
Below is an implementation using just one click handler to handle all four answer buttons.
Include the following JavaScript code:
// JavaScript code here...
And use the following HTML template:
Time: <span class="time">60</span><br>
Score: <span id="score">0</span><br>
<div id="question"></div>
<button class="answer">A</button> <span class="text"></span><br>
<button class="answer">B</button> <span class="text"></span><br>
<button class="answer">C</button> <span class="text"></span><br>
<button class="answer">D</button> <span class="text"></span><br>
<div id="answer-result"></div>