JSFiddle - React, Tailwind, and code Playground
by joshmoto
HTML
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<button id="start">start</button>
<div id="questionPage" style="display: none;">
<h1>Question</h1>
<br>
<p id="question"></p>
<div id="options"></div>
</div>
JavaScript
$(function() {
// our test object
let testMath = {
1: {
question: "1 + 2 = ?",
options: [3, 6],
answer: 3
},
2: {
question: "2 + 7 = ?",
options: [9, 13],
answer: 9
}
};
// constant question page
const questionPage = $('#questionPage');
// render question function
let renderQuestion = function(question) {
// if question id exists in testMath object
if (testMath[question]) {
// render the question
$('#question', questionPage).html(testMath[question].question);
// remove old options
$('#options').empty();
// for each question answer options
testMath[question].options.forEach(function(answer) {
// append answer option button to options
$('#options').append('<button data-question="' + question + '" data-answer="' + answer + '">' + answer + '</button>');
});
} else {
// test complete alert
$(questionPage).empty();
alert('Test Complete!');
}
}
// each options button
$(document).on('click', '#options BUTTON', function() {
// get button data values
let question = $(this).data('question');
let answer = $(this).data('answer');
// check answer
checkAnswer(this, question, answer);
});
// check answer function
let checkAnswer = function(elem, question, answer) {
// if answer is correct
if (answer === testMath[question].answer) {
// render this button text correct and switch off event
$(elem).text('correct').off('click');
// 2 sec delay
setTimeout(function() {
// render next question
nextQuestion(question);
}, 2000);
// else answer is wrong
} else {
// render this button text wrong
$(elem).text("wrong");
// 1 sec delay
setTimeout(function() {
// render wrong answer value back this button
$(elem).text(answer);
}, 1000);
}
}
// next question...