JavaScript quiz tutorial

This tutorial explains how to create a quiz program in the JavaScript language which will look like this (you can change the theme):

quiz

The quiz will look like this when the user has finished it:

quiz_complete

By following this tutorial you will develop the following programming skills:

Please follow the steps below. You can download the complete code at the bottom of this page, but make sure you read the steps so you know what each part of the code is responsible for.

Setting up the HTML code

To begin, create a new html file eg. quiz.html in a coding text editor. You need to add some HTML code in the body section of an html file which will create a heading (in this example it is a h2 size heading) with an id of ‘test_status‘ and a div with an id of ‘test‘. The test_status heading will display the status of the quiz eg. “Question 2 of 4”, or “Test completed”. The ‘test’ div will display the actual questions and possible answers in the quiz. Use the code below to get started.

<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Quiz</title>

</head>
<body>
<h2 id="test_status"></h2>
<div id="test"></div>
</body>

</html>

Now that you have a heading a a div in your HTML code, it is time to apply a style to them by adding some CSS code. In the head section of the HTML file, under the title tags, add the following code:

<style>
div#test{ border:#5AB029 3px solid; padding:10px 40px 40px 40px; background-color:#E5FCE3; width:50%;}
</style>

You can change the code above by changing the border or background colours, border thickness and padding, or adding extra style properties.

Setting up the JavaScript code

Inside the head section of the HTML code under your </style> tag, add the following code:

<script type="text/javascript">
var pos = 0;
var correct = 0;
var test, test_status, question, choice, choices, chA, chB, chC;
</script>

The code above will create several variables. Firstly, the pos variable is used to record what the position the user is at in the test eg. question 3 out of 4. The correct variable stores the number of questions answered correctly. The test variable contains the ‘test’ div and the test_status variable is used to contain the ‘test_status’ heading which displays the user’s progress in the test.

The question variable will contain a question grabbed from an array, the choice variable will contain the user’s selected answer for a question, choices variable will contain the possible answers that will be displayed to the user, and chA, chB, and chC variables will contain each possible answer (A, B, or C) in the multiple choice quiz.

Adding the questions, possible answers, and answer key to the quiz

Now the questions need to be created along with their possible answers and the correct answer (answer key). In this example, we will have four questions (you can add more) with three multiple choice options for each question (A, B or C). To do this, we make a multidimensional array which contains the questions, the options for each question, and the answer key for each question. Add the code below and change the questions to your liking.

This code goes inside the script tags under the variables you created in the previous step.

var questions = [
  ["What is 36 + 42", "64", "78", "76", "B"],
  ["What is 7 x 4?", "21", "27", "28", "C"],
  ["What is 16 / 4?", "4", "6", "3", "A"],
  ["What is 8 x 12?", "88", "112", "96", "C"]
  ];

Create the get function

This quiz needs to get elements from the web page (the heading and the div) and then modify those elements several times. Rather than constantly typing the document.getElementById(); method over and over again, we can simply turn it into a function called get. Add this code inside the script tags after the array you made in the previous step.

function get(x){
  return document.getElementById(x);
}

Create the renderQuestion function

The renderQuestion function will be used to get the ‘test‘ div, check the user’s position in the quiz, and if they have not yet completed the quiz then they will be served different questions. The function will display the user’s progress and the actual question and options to the user. The user must choose an answer by selecting a radio button next to an answer and then click the ‘Submit Answer’ button.

Add this code inside the script tags below the get function you created in the previous step.

function renderQuestion(){
  test = get("test");
  if(pos >= questions.length){
    test.innerHTML = "<h2>You got "+correct+" of "+questions.length+" questions correct</h2>";
    get("test_status").innerHTML = "Test completed";
    // resets the variable to allow users to restart the test
    pos = 0;
    correct = 0;
    // stops rest of renderQuestion function running when test is completed
    return false;
  }
  get("test_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;
  question = questions[pos][0];
  chA = questions[pos][1];
  chB = questions[pos][2];
  chC = questions[pos][3];
  test.innerHTML = "<h3>"+question+"</h3>";
  // the += appends to the data we started on the line above
  test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
  test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}

Create the checkAnswer function

The checkAnswer function is used to, you guessed it…check the answer. While the quiz is incomplete, each user choice will be checked and compared with the correct answer associated with each question (stored in the questions array). At the end of this question being called, the renderQuestion will be called.

Add the code below inside your script tags under the renderQuestion function you created in the previous step.

function checkAnswer(){
  // use getElementsByName because we have an array which it will loop through
  choices = document.getElementsByName("choices");
  for(var i=0; i<choices.length; i++){
    if(choices[i].checked){
      choice = choices[i].value;
    }
  }
  // checks if answer matches the correct choice
  if(choice == questions[pos][4]){
    //each time there is a correct answer this value increases
    correct++;
  }
  // changes position of which character user is on
  pos++;
  // then the renderQuestion function runs again to go to next question
  renderQuestion();
}

Get the quiz to load

The last step involves adding one line of code that will run the renderQuestion function as soon as the page has loaded (using an event listener that checks for a load event). When that function is loaded, the questions will be presented to the user and the quiz will begin.

Add the code below inside your script tags in your code. Add it below the checkAnswer function you created in the previous step. make sure you have ended the script section by closing it with the </script> tag!

window.addEventListener("load", renderQuestion, false);

And that’s it! You have now created a JavaScript quiz game. Challenge yourself by trying to add the following features to your quiz:

  • Add more questions (easy!)
  • Change the quiz theme (background colours/gradient, border, font style, etc)
  • Tell the user which questions they answered incorrectly
  • Display a visual progress bar during the test
  • Display the user’s score as a percentage value
  • Allow the user to re-take the quiz
  • Add more possible answers (eg. A, B, C, D)
  • Store the results in a database using PHP/MySQL (tricky)

Complete code

Here is the complete JavaScript code for the quiz program:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Quiz</title>

<style>
div#test{ border:#5AB029 3px solid; padding:10px 40px 40px 40px; background-color:#E5FCE3; width:50%;}
</style>

<script type="text/javascript">
// pos is position of where the user in the test or which question they're up to
var pos = 0, test, test_status, question, choice, choices, chA, chB, chC, correct = 0;
// this is a multidimensional array with 4 inner array elements with 5 elements inside them
// if you don't want answers viewable in the code, then you should use PHP and mySQL database
var questions = [
  ["What is 36 + 42", "64", "78", "76", "B"],
  ["What is 7 x 4?", "21", "27", "28", "C"],
  ["What is 16 / 4?", "4", "6", "3", "A"],
  ["What is 8 x 12?", "88", "112", "96", "C"]
  ];
// this get function is short for the getElementById function	
function get(x){
  return document.getElementById(x);
}
function renderQuestion(){
  test = get("test");
  if(pos >= questions.length){
    test.innerHTML = "<h2>You got "+correct+" of "+questions.length+" questions correct</h2>";
    get("test_status").innerHTML = "Test completed";
    // resets the variable to allow users to restart the test
    pos = 0;
    correct = 0;
    // stops rest of renderQuestion function running when test is completed
    return false;
  }
  get("test_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;
  question = questions[pos][0];
  chA = questions[pos][1];
  chB = questions[pos][2];
  chC = questions[pos][3];
  test.innerHTML = "<h3>"+question+"</h3>";
  // the += appends to the data we started on the line above
  test.innerHTML += "<input type='radio' name='choices' value='A'> "+chA+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='B'> "+chB+"<br>";
  test.innerHTML += "<input type='radio' name='choices' value='C'> "+chC+"<br><br>";
  test.innerHTML += "<button onclick='checkAnswer()'>Submit Answer</button>";
}
function checkAnswer(){
  // use getElementsByName because we have an array which it will loop through
  choices = document.getElementsByName("choices");
  for(var i=0; i<choices.length; i++){
    if(choices[i].checked){
      choice = choices[i].value;
    }
  }
  // checks if answer matches the correct choice
  if(choice == questions[pos][4]){
    //each time there is a correct answer this value increases
    correct++;
  }
  // changes position of which character user is on
  pos++;
  // then the renderQuestion function runs again to go to next question
  renderQuestion();
}
window.addEventListener("load", renderQuestion, false);
</script>
</head>
<body>
<h2 id="test_status"></h2>
<div id="test"></div>
</body>

</html>