Simple Quiz With Javascript – Free Code Download

Welcome to a tutorial on how to create a simple quiz using Javascript. So you have mastered the ways of “hello world”, and looking for the next piece of the action? A simple quiz is a good place to start, and let us walk through an example in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

Download & Demo How It Works Useful Bits
The End

 

 

DOWNLOAD & DEMO

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SIMPLE QUIZ DEMO

 

 

JAVASCRIPT QUIZ GAME

All right, let us now get into the details of how the quiz game works.

 

STEP 1) THE HTML

js-quiz.html
<!-- (A) LOAD QUIZ CSS + JS -->
<link href="quiz.css" rel="stylesheet">
<script src="quiz.js"></script>
 
<!-- (B) QUIZ CONTAINER -->
<div id="quizWrap"></div>

Yep… That’s all for the HTML. All we need is to include the stylesheet, Javascript, and create an empty <div id="quizWrap"> to generate the quiz.

 

STEP 2) QUIZ QUESTIONS & ANSWERS

quiz.js
// (A) PROPERTIES 
// (A1) QUESTIONS & ANSWERS
// Q = QUESTION, O = OPTIONS, A = CORRECT ANSWER
data: [
{
  q : "What is the standard distance between the target and archer in Olympics?",
  o : [
    "50 meters",
    "70 meters",
    "100 meters",
    "120 meters"
  ],
  a : 1 // arrays start with 0, so answer is 70 meters
},
{
  q : "Which is the highest number on a standard roulette wheel?",
  o : [
    "22",
    "24",
    "32",
    "36"
  ],
  a : 3
},
{
  q : "How much wood could a woodchuck chuck if a woodchuck would chuck wood?",
  o : [
    "400 pounds",
    "550 pounds",
    "700 pounds",
    "750 pounds"
  ],
  a : 2
},
{
  q : "Which is the seventh planet from the sun?",
  o : [
    "Uranus",
    "Earth",
    "Pluto",
    "Mars"
  ],
  a : 0
},
{
  q : "Which is the largest ocean on Earth?",
  o : [
    "Atlantic Ocean",
    "Indian Ocean",
    "Arctic Ocean",
    "Pacific Ocean"
  ],
  a : 3
}
]

What does a quiz need? Questions and answers, so we begin by defining some. 😕 This can be kind of confusing for beginners, so look carefully.

  • quiz.data is an array of objects. That is, [{FIRST QUESTION}, {SECOND QUESTION}, {THIRD QUESTION}].
  • In each question, { q:QUESTION, o:OPTIONS, a:CORRECT ANSWER }.
    • o is an array of the available options (there can be more than 4).
    • a specifies which is the correct answer. That is, a:0 will specify that the first option is correct.

 

 

STEP 3) GAME FLAGS

quiz.js
// (A2) HTML ELEMENTS
hWrap: null, // HTML quiz container
hQn: null, // HTML question wrapper
hAns: null, // HTML answers wrapper
 
// (A3) GAME FLAGS
now: 0, // current question
score: 0, // current score

Next, we have a bunch of properties. These should be pretty self-explanatory – Reference to HTML elements, and flags to keep track of the current score/question.

 

STEP 4) INITIALIZE QUIZ (BUILD HTML)

quiz.js
// (B) INIT QUIZ HTML
init: () => {
  // (B1) WRAPPER
  quiz.hwrap = document.getElementById("quizWrap");
    
  // (B2) QUESTIONS SECTION
  quiz.hqn = document.createElement("div");
  quiz.hqn.id = "quizQn";
  quiz.hwrap.appendChild(quiz.hqn);
    
  // (B3) ANSWERS SECTION
  quiz.hans = document.createElement("div");
  quiz.hans.id = "quizAns";
  quiz.hwrap.appendChild(quiz.hans);
    
  // (B4) GO!
  quiz.draw();
}
window.addEventListener("load", quiz.init);

quiz.init() is called on window load, and all it does is insert 2 HTML elements into <div id="quizWrap"> from step 1.

  • <div id="quizQn"> To display the question.
  • <div id="quizAns"> To display the options.

 

 

STEP 5) DRAW CURRENT QUESTION

quiz.js
// (C) DRAW QUESTION
draw: () => {
  // (C1) QUESTION
  quiz.hqn.innerHTML = quiz.data[quiz.now].q;
    
  // (C2) OPTIONS
  quiz.hans.innerHTML = "";
  for (let i in quiz.data[quiz.now].o) {
    let radio = document.createElement("input");
    radio.type = "radio";
    radio.name = "quiz";
    radio.id = "quizo" + i;
    quiz.hans.appendChild(radio);
    let label = document.createElement("label");
    label.innerHTML = quiz.data[quiz.now].o[i];
    label.setAttribute("for", "quizo" + i);
    label.dataset.idx = i;
    label.addEventListener("click", () => { quiz.select(label); });
    quiz.hans.appendChild(label);
  }
}

quiz.draw() is called right after quiz.init() and after the user picks an option in draw.select(). This should be self-explanatory again, draw the current question and options.

 

 

STEP 6) SELECT AN OPTION

quiz.js
// (D) OPTION SELECTED
select: (option) => {
  // (D1) DETACH ALL ONCLICK
  let all = quiz.hAns.getElementsByTagName("label");
  for (let label of all) {
    label.removeEventListener("click", quiz.select);
  }
 
  // (D2) CHECK IF CORRECT
  let correct = option.dataset.idx == quiz.data[quiz.now].a;
  if (correct) { 
    quiz.score++; 
    option.classList.add("correct");
  } else {
    option.classList.add("wrong");
  }
 
  // (D3) NEXT QUESTION OR END GAME
  quiz.now++;
  setTimeout(() => {
    if (quiz.now < quiz.data.length) { quiz.draw(); } 
    else {
      quiz.hQn.innerHTML = `You have answered ${quiz.score} of ${quiz.data.length} correctly.`;
      quiz.hAns.innerHTML = "";
    }
  }, 1000);
}

Lastly, when the user picks an option – quiz.select() will determine if it is the correct answer, keep track of the score, then show the next question.

 

EXTRA) RESTARTING THE QUIZ

quiz.js
// (E) RESTART QUIZ
reset : () => {
  quiz.now = 0;
  quiz.score = 0;
  quiz.draw();
}

Simply call quiz.reset() to reset the quiz. For example, add a simple reset button at the end of the quiz. Section D3 – quiz.hAns.innerHTML = "<input type='button' value='Try Again' onclick='quiz.reset()'>";

 

 

USEFUL BITS & LINKS

That’s all for the code, and here are a few small extras that may be useful to you.

 

SIMPLE JAVASCRIPT GAMES

If you are interested in learning more about creating simple classic games, do check out my other guides:

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand the basics of Javascript, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

6 thoughts on “Simple Quiz With Javascript – Free Code Download”

  1. Thank you this useful code. I’m trying as teacher the submit bridge game quizzes. How can I reload, on the fly – using a button, the same set of questions? I have not a sound graps of JS (working within Oracle)
    Cheers.
    Jean-Pierre @Paris

Leave a Comment

Your email address will not be published. Required fields are marked *