How to make a simple JavaScript quiz

What you'll create

See the Pen Simple JavaScript Quiz by Yaphi (@yaphi1) on CodePen.

To make a simple JavaScript quiz, there are four steps:
  1. Set up the structure
  2. Show the questions
  3. On submit, show the results
  4. Put it all together

The point of this tutorial is to make the simplest possible JavaScript quiz without any external code needed.

We'll also avoid animations, excessive styles, and anything else that will distract from the JavaScript quiz.

A Quick Note Before You Start:

This tutorial assumes a basic understanding of JavaScript. If you're not there yet, I've put together a JavaScript road map to get you comfortable with practical concepts quickly.

Step 1: Set up the structure

First, we'll create divs to hold our quiz and our results.

Then we'll put in a submit button.

Here's the HTML:


			<div id="quiz"></div>
			<button id="submit">Get Results</button>
			<div id="results"></div>
		

Next, we'll create a function to generate a quiz.

Your function will need these inputs:

  • The quiz questions
  • A place to put the quiz
  • A place for the results
  • A submit button

And if you put those things in, the function should spit out a fully-formed quiz.

The JavaScript structure:


			function generateQuiz(questions, quizContainer, resultsContainer, submitButton){

				function showQuestions(questions, quizContainer){
					// code will go here
				}

				function showResults(questions, quizContainer, resultsContainer){
					// code will go here
				}

				// show the questions
				showQuestions(questions, quizContainer);

				// when user clicks submit, show results
				submitButton.onclick = function(){
					showResults(questions, quizContainer, resultsContainer);
				}
			}
		

If you look closely at the JavaScript structure, you'll see that our generateQuiz function contains helper functions to show the quiz, accept submissions, and show the results.

Step 2: Show the questions

First we'll need the questions, so put this in your JavaScript:


			var myQuestions = [
				{
					question: "What is 10/2?",
					answers: {
						a: '3',
						b: '5',
						c: '115'
					},
					correctAnswer: 'b'
				},
				{
					question: "What is 30/3?",
					answers: {
						a: '3',
						b: '5',
						c: '10'
					},
					correctAnswer: 'c'
				}
			];
		

Next we'll need a way to show our questions.

For this, we'll fill out our showQuestions function.

The general idea:
For each question, show the question along with all of its answer choices. Read through the comments in this code to see how it works.


			function showQuestions(questions, quizContainer){
				// we'll need a place to store the output and the answer choices
				var output = [];
				var answers;

				// for each question...
				for(var i=0; i<questions.length; i++){
					
					// first reset the list of answers
					answers = [];

					// for each available answer to this question...
					for(letter in questions[i].answers){

						// ...add an html radio button
						answers.push(
							'<label>'
								+ '<input type="radio" name="question'+i+'" value="'+letter+'">'
								+ letter + ': '
								+ questions[i].answers[letter]
							+ '</label>'
						);
					}

					// add this question and its answers to the output
					output.push(
						'<div class="question">' + questions[i].question + '</div>'
						+ '<div class="answers">' + answers.join('') + '</div>'
					);
				}

				// finally combine our output list into one string of html and put it on the page
				quizContainer.innerHTML = output.join('');
			}
		

Once that's ready, you can run the function like this:


			showQuestions(questions, quizContainer);
		

Note that in this line, the questions and quizContainer values will come from your generateQuiz function.

The nice part about our code is that it works for any number of questions or answer choices you might have in your JavaScript quiz.

Step 3: On submit, show the results

We'll need to fill out our showResults function to show the results of our quiz.

Here's how our JavaScript logic will look:

  • For each question, find the selected answer
  • If the answer is correct, respond accordingly
  • If the answer is wrong, respond accordingly
  • Show the number of correct answers out of the total

And here's the JavaScript to show the results of our quiz:


			function showResults(questions, quizContainer, resultsContainer){
				
				// gather answer containers from our quiz
				var answerContainers = quizContainer.querySelectorAll('.answers');
				
				// keep track of user's answers
				var userAnswer = '';
				var numCorrect = 0;
				
				// for each question...
				for(var i=0; i<questions.length; i++){

					// find selected answer
					userAnswer = (answerContainers[i].querySelector('input[name=question'+i+']:checked')||{}).value;
					
					// if answer is correct
					if(userAnswer===questions[i].correctAnswer){
						// add to the number of correct answers
						numCorrect++;
						
						// color the answers green
						answerContainers[i].style.color = 'lightgreen';
					}
					// if answer is wrong or blank
					else{
						// color the answers red
						answerContainers[i].style.color = 'red';
					}
				}

				// show number of correct answers out of total
				resultsContainer.innerHTML = numCorrect + ' out of ' + questions.length;
			}
		

In the line that says "//find selected answer", we did a little trick. We used the || operator, which means "or" to basically say "Give us the selected answer OR if there's not one, then just give us an empty object." That way, trying to get the .value will give us undefined instead of causing an error.

That way, the quiz won't break if someone skips a question.

Show quiz results on submit

The next step is to show quiz results when someone clicks the submit button.

The following JavaScript will make that happen:


			// on submit, show results
			submitButton.onclick = function(){
				showResults(questions, quizContainer, resultsContainer);
			}
		

Note that the submitButton variable comes from our original generateQuiz function as one of the parameters.

Step 4: Put it all together

Now that you have the pieces, you can generate your very own JavaScript quiz.

You have the questions in the myQuestions variable from Step 2. Now you need to let your JavaScript know which HTML elements to use for the quiz, the results, and the submit button.


			var quizContainer = document.getElementById('quiz');
			var resultsContainer = document.getElementById('results');
			var submitButton = document.getElementById('submit');
		

Now that everything's in place, you can generate your JavaScript quiz!


			generateQuiz(myQuestions, quizContainer, resultsContainer, submitButton);
		

Congrats!

Bonus: The fun part

Now that you have the basic idea of how to make a JavaScript quiz, you can try styling the elements however you want.

Sample CSS used in demo:


			body{
				font-size: 20px;
				font-family: sans-serif;
				color: #333;
			}
			.question{
				font-weight: 600;
			}
			.answers {
			    margin-bottom: 20px;
			}
			#submit{
				font-family: sans-serif;
				font-size: 20px;
				background-color: #297;
				color: #fff;
				border: 0px;
				border-radius: 3px;
				padding: 20px;
				cursor: pointer;
				margin-bottom: 20px;
			}
			#submit:hover{
				background-color: #3a8;
			}
		

Feel free to change whatever you want!