How to create a quiz in JavaScript?

How to create a quiz in JavaScript?
How to create a quiz in JavaScript?

This is a tutorial for dummies and aliens. The JavaScript Quiz is one of the essential projects you should build as a web developer if you wish to add fun interactivity to your web pages later.

JavaScript is a powerful language that makes everything possible. The beauty of the syntax makes all kinds of learners and developers understand the language with ease and astounding pieces of technology are created. If you follow this blog religiously you will be able to understand the concepts of JavaScript that will enable you to perform the undermentioned tasks like a pro:

  • Adding interactivity to your web page on the click of a button
  • Changing the text on your web page as per the user interaction
  • Show and Hide certain elements to your web page with JavaScript

A tip before we dive in, in case you are unable to understand any code snippet, re-read the description that has been written with the snippet, if that doesn’t help, look it up online. A part of being a great developer is possessing the ability to find references that aid you in understanding the code and fix bugs within your code.

Setup & Requirements

The preferred requirements for building this quiz are specified below. While these requirements are not mandatory, it is advised to use them for a better coding experience.

Browser: Google Chrome (make sure you have installed the latest version)
Editor: Visual Studio Code
Extensions (for VSC): Live Server, CSS Formatter, HTML Snippets, Debugger for Chrome

JavaScript Quiz format 1: Selection between two choices

In this format, users will be given one question for which they will have two options to choose from. Based on the user choice, the score will be incremented. Upon selection of an option, the next question appears automatically, however previous and next buttons are available on the page for better user experience. This format will serve as a practice test for the user as she will be able to go back to the questions and select the options to get a cent percent score.

In addition to this, a submit and a restart button is introduced, the functionality of which is exactly what their name suggests. Before beginning with building any webpage, you need to have a clear picture in your head about what exactly are you going to build. It is important to create a wireframe of the final output of your page to proceed in a structured manner and not leave out any details or functionalities while are coding

Figure 1 JS Quiz Format 1 Wireframe

I have created this wireframe using Figma. You can either use Figma or any other design tool available or you can even draw it on a piece of paper. The motive is to pen down every detail of your product/project.

If you are using VSC and have installed all the extensions mentioned in setup and requirements, create a new file and name it index.html. Now, type HTML and select the html:5 option, an HTML boilerplate will be created automatically. Change the title of the page from Document to JavaScript Quiz Format 1 or any other fun name you can think of.

Figure 2 HTML Boilerplate

Divide your wireframe into components in your mind and start writing some code in your index.html file.

  • A background container where your text and buttons will be visible.
  • A div container to store the score.
  • A div container to display the question.
  • A div container which contains the choices you want to provide to the user for selecting an answer to the question. (Combine 3 and 4 in one separate container)
  • A div container which contains all the control buttons: Restart, Prev, Next and Submit.

Add relevant classes to all the div containers which will help in styling them later and relevant IDs which will enable you to add JavaScript interactivity later. Keep in mind that you should never be lazy in naming your classes and IDs. It is beneficial for you as well as the person who might read your code to understand exactly which component of your webpage is being mentioned.

This is how your body tag should look now:

Figure 3 HTML Body Code

This is how your web page should look like at this point:

Figure 4 Output after writing HTML Code

We have now added everything we needed to our page, it is time to style our page and make it look presentable.

The first step to a beautiful webpage is to make sure you are using the right typography. I have used one of my favourite Google Fonts – Poppins and you can find this font here. For those who are using Google Fonts for the first time, you need to select the variations of the font you require on your webpage, a selected family sidebar will pop up.

You can either use the <link></link> variation of the font and add it to your index.html file or use the @import variation and add it to your style.css file. I have used the @import variation but you can feel free to experiment.

Figure 5 Importing the Google Font – Poppins

Select all elements using the universal selector and make sure you get rid of the auto margin and auto padding on the webpage. Unless you explicitly have to use multiple fonts on your webpage, this is where you have to add in the font-family for all the elements on your page.

Figure 6 CSS – Universal Selector

Give the body a nice background gradient, by default the gradient will be repeated in strips on your webpage, make sure you get rid of that using the no-repeat property. To fill your entire screen with the beautiful gradient you created, specify the height and width of your body as 100% of your viewport height and 100% of your viewport width respectively. For easy and quick vertical and horizontal alignment, use CSS Flexbox and change the display of the body to flex and specify central vertical and horizontal alignment.

Figure 7 CSS – Body

The container which will contain the question, score, options and buttons need to be made now. To ensure that your container doesn’t blend with the background, give a nice light shade to it in contrast with the background. To give a 3D effect, use the CSS box-shadow property. Specify the height and width relative to the viewport in vh and vw units respectively.

We also want to make sure that the elements inside this container are perfectly aligned to centre both horizontally and vertically. For this, we once again put CSS Flexbox to use, here we have used an additional property of flex-direction to specify how our elements will be stacked. Rounder corners are preferred more than sharp edges, and hence, a nice border-radius is also given to our container.

Figure 8 CSS – Container

The stylising of the score counter will be fairly simple, the font size, weight and font colour have to be controlled. I have used colours in contrast with the background to give a nice blend of all the elements and have also used different colours for the total score and the score of the user. You are free to experiment with colours and different styles on your own.

Figure 9 CSS – Score

The div container with the class content will contain the text of the question and the options for that particular question. The CSS for the same will contain properties that make certain the elements inside the content container will be centrally aligned both vertically and horizontally.

Figure 10 CSS – Content

Now we will stylise the buttons on our page. Since these buttons are our primary call to action, we need to make sure that the readability is maximum. On a dark background, light text color is used which is the same as that of the background. Whenever we are choosing the color scheme for our web page, we need to make sure that all the colors are in contrast with one another so that everything looks connected as a part of one element.

Some box-shadow is also added to give a nice effect. I have changed the cursor type to pointer here to differentiate the clickable and non-clickable elements on my page. For more effect, I have also added a hover functionality which will make the button in focus stand out from the rest of the buttons.

Figure 11 CSS – Buttons

Add some padding to the options and controls classes.

Figure 12 CSS – Options Controls

It is now time to add the magic that we need in our code, the class that will handle the hiding and showing of elements on our webpage.

We have now completed stylising our page. This is how our website looks now. Isn’t it pretty?

Figure 14 Output after adding CSS

Moving on to the most fun part of this entire game, adding JavaScript! Before proceeding, make sure there is no error in the style of your webpage and you have added the “hide” class for sure, it is an extremely crucial element for the working of our quiz game.

The first step is to create variables that represent the elements in our document. These variables will be used to access the elements via the DOM model.

Figure 15 JavaScript – Const Variables

Next, we would be defining our own variables which will be used to maintain three important things for the interactivity on our webpage:

  • A counter for the current question. This will enable JavaScript to access the right question by incrementing or decrementing this counter based on the user’s interactivity with previous and next buttons.
  • A counter for the score. For every correct answer, the score will be incremented. However, in cases where you have to introduce negative marking to your quiz, the score will be decremented for every incorrect answer.
  • An array of questions. This will contain our questions and the options for the same.
Figure 16 JavaScript – Custom Variables

Add onclick events to the button. This will call respective functions when a particular button is clicked.

Figure 17 JavaScript – OnClick Events

Create a function beginQuiz() that will get executed when the page loads and the script gets executed. We have also added a feature that will allow the page to jump to the next question once an option is selected from the list of answer options.

Figure 18 JavaScript – Begin Quiz

Create a function restart() that will reset the score, the current question index and remove the hide class from elements if they are added to them and call beginQuiz().

Figure 19 JavaScript - Restart
Figure 19 JavaScript – Restart

Create a function next() that will jump to the next question. Here the currentQuestion will be incremented and the hidden class will be removed from the prev button. Based on the option the user selects, the score will be incremented.

Figure 20 JavaScript – Next()

Create a function prev() that will jump to the previous question. Here the currentQuestion will be decremented and the hidden class will be removed from the next button. Based on the option the user selects, the score will be incremented.

Figure 21 JavaScript – Prev()

Finally, create the submit button which will hide all elements except the restart button and score. It will also add a congratulatory message to our page.

Figure 22 JavaScript – Submit()

You have now successfully created your quiz!

DIY JAVASCRIPT QUIZZES

Here wireframes for two more formats are attached which you have to try on your own. The concepts used will be similar to the ones you understood in this tutorial. Present the final output of your code on your social media handles and tag Coding Ninjas.

Format 2: MCQ Quiz

Figure 23 Wireframe – JavaScript Quiz Format 2
Figure 24 Wireframe - JavaScript Quiz Format 2 (Results)
Figure 24 Wireframe – JavaScript Quiz Format 2 (Results)

Format 3: MCQ Quiz with Timer

Figure 25 Wireframe – JavaScript Quiz Format 3
Figure 26 Wireframe – JavaScript Quiz Format 3 (Results)

We hope that you liked reading the article, to explore our courses, click here.

By Pooja Gera