This JavaScript code snippet helps you to create multiple choice quiz. It defines variables and functions to populate a quiz game with questions and answers. The variables “quesIndex” and “timeAllotted” store the current question index and the time allotted for the game in seconds, respectively. The variable “questionBank” is an array of objects, each containing a question, a set of possible answers with IDs, the ID of the correct answer, and a reason why the answer is correct. The functions “populateQuestionDetails()”, “renderQuesControls()”, “getPreviousQuestion()”, “getNextQuestion()”, and “processAnswer()” handle the logic for displaying the current question and answers, rendering the appropriate controls for moving between questions, and processing the user’s answer.
Finally, the function “updateClock()” is used to decrement the remaining time and end the game when the time runs out. The code also hides certain elements until the game is started.
How to Create JavaScript Multiple Choice Quiz Code With Timer
Create the HTML structure for the multiple-choice quiz as follows:
<!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <div class="container"> <header> <div class="col-md-8 col-md-offset-2"> <h2 class="text-center">Ray's Trivia Game</h2> <hr> </div> </header> <div id="main-game"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="timer text-center" id="game-timer">30</div> <div class="jumbotron text-center" id="question-container">I am a Question??? </div> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="text-center" id="answers-container"> <div class="answer" data-content="1000">I am an answer.</div> <div class="answer" data-content="1001">I am an answer.</div> <div class="answer" data-content="1002">I am an answer.</div> <div class="answer" data-content="1003">I am an answer.</div> </div> </div> </div> </div> </div> <div class="row top-buffer"> <div class="col-md-8 col-md-offset-2"> <div class="well" id="answer-response">I am the explanation to the answer.</div> </div> </div> <hr> <footer> <div class="row"> <div class="col-md-8 col-md-offset-2"> <button class="btn btn-primary pull-left" id="previousQ"> Previous </button> <button class="btn btn-primary pull-right" id="nextQ"> Next </button> <button class="btn btn-primary pull-right" id="finish"> Finish </button> </div> </div> </footer> </div> <div id="splash-screen" class="container top-buffer"> <div class="row"> <div class="col-md-offset-2 col-md-8"> <div class="jumbotron text-center"> <h2>Welcome to US Trivia!<br>Good Luck!</h2> <div class="small">(This is a timed quiz of only 30 seconds)</div> </div> </div> </div> <div class="row"> <div class="col-md-offset-2 col-md-8 text-center"> <button id="start" class="btn btn-primary btn-lg">Start US Trivia</button> </div> </div> </div> <div id="results-display" class="container top-buffer"> <div class="row"> <div class="col-md-offset-2 col-md-8 text-center"> <h4>Here's how you did.</h4> <div class="well" id="answerHistory"> <table class="table"> <thead> <tr> <th>Question</th> <th>You answered</th> <th>The correct answer</th> <th>Status</th> </tr> </thead> <tbody id="result-rows"> </tbody> </table> </div> </div> </div> <div class="row"> <div class="col-md-offset-2 col-md-8 text-center"> <button id="restart" class="btn btn-lg btn-primary">Restart</button> </div> </div> </div> </div>
Now, style the multiple choice quiz using the following CSS styles:
body { background-color: #333; } .timer { color: #f49242; font-weight: bold; font-size: 1.6em; padding: 6px; margin: 0px auto 10px; border: 1px solid #c6c6c2; border-radius: 5px; width: 80px; } .answer{ width: 100%; border:1px solid #a8c1d5; -webkit-border-radius: 3px; -moz-border-radius: 3px;border-radius: 3px;font-size:12px;font-family:arial, helvetica, sans-serif; padding: 10px 10px 10px 10px; text-decoration:none; display:inline-block;text-shadow: -1px -1px 0 rgba(0,0,0,0.3);font-weight:bold; color: #FFFFFF; background-color: #CEDCE7; background-image: -webkit-gradient(linear, left top, left bottom, from(#CEDCE7), to(#596a72)); background-image: -webkit-linear-gradient(top, #CEDCE7, #596a72); background-image: -moz-linear-gradient(top, #CEDCE7, #596a72); background-image: -ms-linear-gradient(top, #CEDCE7, #596a72); background-image: -o-linear-gradient(top, #CEDCE7, #596a72); background-image: linear-gradient(to bottom, #CEDCE7, #596a72);filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr=#CEDCE7, endColorstr=#596a72); } .cd__main{ display: block !important; } .answer:hover{ border:1px solid #8aabc5; background-color: #acc4d6; background-image: -webkit-gradient(linear, left top, left bottom, from(#acc4d6), to(#434f55)); background-image: -webkit-linear-gradient(top, #acc4d6, #434f55); background-image: -moz-linear-gradient(top, #acc4d6, #434f55); background-image: -ms-linear-gradient(top, #acc4d6, #434f55); background-image: -o-linear-gradient(top, #acc4d6, #434f55); background-image: linear-gradient(to bottom, #acc4d6, #434f55);filter:progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr=#acc4d6, endColorstr=#434f55); } .top-buffer { margin-top: 20px; }
Finally, add the following JavaScript function for its functionality:
var quesIndex; var gameTimer; var timeAllotted = 15; //seconds var questionBank = [ { question:"What is the capital of Alaska?", answers:[ {ansID: 1000, answer:"Anchorage"}, {ansID: 1001, answer:"Barrow"}, {ansID: 1002, answer:"Juneau"}, {ansID: 1003, answer:"Fairbanks"}, ], correct: 1002, selected: null, reason: "It's Juneau, which still has a population of less than 33,000. Yikes." }, { question:"Who founded the US Treasury?", answers:[ {ansID: 1003, answer:"James Madison"}, {ansID: 1004, answer:"Alexander Hamilton"}, {ansID: 1005, answer:"Benjamin Franlkin"}, {ansID: 1006, answer:"Andrew Jackson"}, ], correct: 1004, selected: null, reason: "Alexander Hamilton was a major contrinutor to the strucure of the formative years of the US government. Arguably his largest contribution, apart from being a major contributor to maturing the constitution itself, was managing and growing the fledgling US credit system." }, { question:"Who is the first American born president?", answers:[ {ansID: 1007, answer:"George Washington"}, {ansID: 1008, answer:"Thomas Jefferson"}, {ansID: 1009, answer:"Andrew Jackson"}, {ansID: 1010, answer:"Martin Van Buren"}, ], correct: 1010, selected: null, reason: "Martin Van Buren was born in December 5th, 1782 in Kinderhook, NY. The first president not born under British rule and the first president not of British ancestry. He was of Dutch lineage." }, { question:"Which was not a part of the original 13 colonies?", answers:[ {ansID: 1011, answer:"Vermont"}, {ansID: 1012, answer:"Georgia"}, {ansID: 1012, answer:"North Carolina"}, {ansID: 1013, answer:"Pennsylvania"}, ], correct: 1011, selected: null, reason: "Vermont was the 14th state which joined on March 4th, 1791." }, { question: "How many time zones does the USA have?", answers:[ {ansID: 1014, answer:"Three"}, {ansID: 1015, answer:"Four"}, {ansID: 1016, answer:"Five"}, {ansID: 1017, answer:"Six"}, ], correct: 1017, selected: null, reason: "Eastern, Central, Mountain, Pacific, Alaskan, and Hawaii-Aleutian" }, ]; function populateQuestionDetails() { $("#answer-response").hide(); $("#question-container").empty(); $("#answers-container").empty(); $("#answer-response").empty(); $("#question-container").html(questionBank[quesIndex].question); var quesAnswers = questionBank[quesIndex].answers; for (var i=0; i < quesAnswers.length; i++) { $("#answers-container").append('<div class="answer" data-content="' + quesAnswers[i].ansID + '">' + quesAnswers[i].answer + '</div>'); } renderQuesControls(); } function renderQuesControls() { if (quesIndex === 0) { $("#previousQ").hide(); $("#nextQ").show(); } else if (quesIndex === questionBank.length-1) { $("#previousQ").show(); $("#nextQ").hide(); $("#finish").show(); } else { $("#previousQ").show(); $("#nextQ").show(); } // console.log("quesIndex: " + quesIndex + " length: " + questionBank.length); } function getPreviousQuestion() { quesIndex--; populateQuestionDetails(); } function getNextQuestion() { quesIndex++; populateQuestionDetails(); } function processAnswer() { var selectedAnsID = parseInt($(this).attr("data-content")); var correctAnsID = questionBank[quesIndex].correct; if (selectedAnsID === correctAnsID) { $("#answer-response").html("<h4>Correct!</h4>"); } else { $("#answer-response").html("<h4>Sorry that's not right.</h4>"); } $("#answer-response").append(questionBank[quesIndex].reason); $("#answer-response").show(); //save the answer the user selected in the questionBank questionBank[quesIndex].selected = selectedAnsID; console.log(questionBank[quesIndex].selected); } $(document).ready(function () { //pre init routine $("#main-game").hide(); $("#results-display").hide(); $("#previousQ").hide(); $("#nextQ").hide(); $("#finish").hide(); }); function updateClock() { timeAllotted--; $("#game-timer").html(timeAllotted); if (timeAllotted === 0) { clearInterval(gameTimer); endGame(); } } $("#start").on("click", function () { $("#splash-screen").hide(); $("#main-game").show(); gameTimer = setInterval(updateClock, 1000); quesIndex = 0; populateQuestionDetails(quesIndex); }); /* Here's a neat trick: for elements that are dynamically created existing handlers pointed to that type of element (via class or id, whichever) will not be automatically bound. Instead of $("[.|#]identifier").on("click", function) bind it to the document for it's id/class as shown below. */ $(document).on("click", ".answer", processAnswer); $("#previousQ").on("click", getPreviousQuestion); $("#nextQ").on("click", getNextQuestion); $("#finish").on("click", endGame); function endGame() { $("#main-game").hide(); processResults(); $("#results-display").show(); } $("#restart").on("click", function () { console.log("reload the game."); window.location.reload() }); function processResults() { var status; var correct = 0; var incorrect = 0; var score = 0; for (var i=0; i < questionBank.length; i++) { if (questionBank[i].correct === questionBank[i].selected) { correct++; status = "Correct!"; } else { incorrect++; status = "Incorrect!"; } //sorry the below is verbose. I know :( I could only see so far ahead. If I had more time I'd refactor it to end cleaner. if (questionBank[i].selected !== null) { //get selected text var selectedText = "NA"; for (var j=0; j < questionBank[i].answers.length; j++) { if (questionBank[i].answers[j].ansID === questionBank[i].selected) { selectedText = questionBank[i].answers[j].answer; break; } } } else { selectedText = "--"; } //get correct ans text var correctText = "NA"; for (var k=0; k < questionBank[i].answers.length; k++) { if (questionBank[i].answers[k].ansID === questionBank[i].correct) { correctText = questionBank[i].answers[k].answer; break; } } $("#result-rows").append("<tr><td>" + questionBank[i].question + "</td><td>" + selectedText + "</td><td>" + correctText + "</td><td>" + status + "</td></tr>"); } }
That’s all! hopefully, you have successfully created the JavaScript multiple choice quiz code with timer. If you have any questions or suggestions, feel free to comment below.