JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html dir = "ltr" lang = "en-US" class = "no-js">
<head>
<title>Test</title>
</head>
<body>
<h1>-Test v1-</h1>
<h2>Simple Math</h2>
<div id="container">
<div id="counter"><span id="numRight">0</span> of <span id="numQuestions">0</span></div>
<div id="question"></div>
<div id="answers"></div>
</div>
</body>
</html>
CSS
h1 {
text-align: center;
margin: 1em;
font-size: 30px;
font-weight: bold;
}
h2 {
text-align: center;
margin: 1em;
font-size: 26px;
}
#container {
text-align: center;
width: 300px;
margin: 0 auto;
}
#counter {
position: absolute;
top: 10px;
left: 10px;
}
#question {
font-size: 20px;
color: blue;
}
#answers button {
width: 100px;
padding: 10px;
display: block;
margin: 6px auto;
}
JavaScript
// Array of objects that contains the information for each question
var questions = [
{
question: 'What is 0 / 6 ?',
options: ['0','1','2'],
answerIdx: 0
},
{
question: 'What is 2 + 2 ?',
options: ['72','4','3.5'],
answerIdx: 1
}
],
i,
numRight = 0,
numQuestions = 0,
answerDiv = document.getElementById('answers'),
questionDiv = document.getElementById('question'),
numRightSpan = document.getElementById('numRight'),
numQuestionsSpan = document.getElementById('numQuestions');
// Display the first question
// Array.shift() removes and returns the first element in an array
displayQuestion(questions.shift());
/**
*
* displayQuestion( q )
* - q = question object
*
*/
function displayQuestion(q) {
// display the question itself
questionDiv.innerHTML = q.question;
// remove any existing buttons from answerDiv
answerDiv.innerHTML = '';
// for each option in the 'options' array, create a button
for(i = 0; i < q.options.length; i++) {
btn = document.createElement('button');
btn.innerHTML = q.options[i];
btn.setAttribute('id',i);
// create the click handler for the button
btn.onclick = function() {
var id = parseInt(this.getAttribute('id'),10);
numQuestionsSpan.innerHTML = ++numQuestions;
// if the id of the button matches the answer index,
// the user was right, so increment numRight and display it
if(id === q.answerIdx) {
numRightSpan.innerHTML = ++numRight;
}
// if there are more questions to be displayed,
// run the function again
if(questions.length) {
displayQuestion(questions.shift());
} else {
alert('Done! You got '+numRight+' of '+numQuestions+'...