How to create a Simple JavaScript Quiz ?

15 Aug, 2021
JavaScript is useful for making any web page a dynamic one. In this article, we are going to see how we can make a simple Quiz Web App using JavaScript.
This Quiz Web App will have the following features.
User Interface for Question and four interactive options.
Navigation between questions.
Evaluation in the form of True or False output values.
Approach: For the user interface, the page is divided into four divisions using HTML div tags and given classes and ids to identify them. The classes and Ids names are chosen such that it carries the purpose of each div.
The first “div” is for “result” which will be used to show the status of the question if the selected answer is correct or not.
The second “div” is for “question-container” which will be used for holding the question text and display them.
The third “div” is for “option-container” as the name suggests, it will hold all four options for the question.
The fourth “div” is for “navigation” which will have a button for navigating to the next question and to evaluate the selected answer.
All of these four “div” are inside another “div” with class “panel”. We are using this DOM element in our script. 
 
Example:
HTML Code: The following code demonstrates the design part of the quiz app.
index.html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <link rel="stylesheet" href="style.css">   </head><body>    <div class="panel">        <div class="result">          </div>        <div class="question-container" id="question">            Question goes here.        </div>        <div class="option-container">            <button class="option" onclick="" id="op1" >option1</button>                  <button class="option" id="op2" >option2</button>                  <button class="option" id="op3">option3</button>                  <button class="option" id="op4">option4</button>        </div>        <div class="navigation">            <button class="evaluate">Evaluate</button>            <button class="next">Next</button>        </div>    </div>    <script src="script.js"></script></body></html>
CSS code: The CSS helps in aligning different options and buttons. The :hover property is responsible for creating the effect of selecting the option. We are also going to change the selection effect using JavaScript.
The code takes care of the looks and alignment of the user interface. The file is included in the head section of the above code.
style.css
body{    padding: 0;    margin: 0;        width:100vw;    height: 100vh;    }.panel{    height: 100vh;    display: flex;    flex-direction: column;    justify-content: center;    align-items: center;}.question-container{    margin: 10px;    padding: 5px;    width: 80vw;    height: 10vh;    background-color: #c7dddf;    font-size: x-large;    text-align: center;      }.result{    margin: 10px;    padding: 5px;    width:80vw;    height: 10vh;    text-align: center;    font-size: 50px;      }.option-container{    display: flex;    justify-content: space-around;     margin: 10px;    padding: 5px;    width: 80vw;    height: 20vh;    background-color: #9eb1b3;           }.option{        padding: 10px;    width: 15vw;    height: 10vh;    font-size: larger;    background-color: lightskyblue;    border-radius: 25%;}.option:hover{    background-color: lightgoldenrodyellow;}.navigation{    width: 80vw;    height: 10vh;    margin: 10px;    padding: 5px;    display: flex;    justify-content: space-around;    background-color:#c7dddf;}  .evaluate,.next{    width:30vw;    height: 8vh;    padding: 5px;    font-size: larger;}.evaluate{        background-color: #50DBB4;}.next{    color: white;    background-color: #BF3325;}
JavaScript code: We are going to dynamically display the question and options, for that, we have created an array of objects, in which each object has a question and corresponding options and the information of the correct answer. With this array of objects, we have the JSON format so it helps us to deal with the API and to deal with the real data which is of JSON type most of the time.
 
Let’s see how we can access different things from this array “Questions”:
Note: The “id” keep changing based on the question number, it represents the question number from the array.
The Questions array is defined. We have taken one boolean variable “start” which is initially set as true indicating the start of the Quiz. The iterate() function is responsible for displaying questions and options based on the “id” passed to it. This function is called conditionally using the “next” button later in the code.
Working of iterate() function: We are getting the result from HTML div and setting it to empty text using the HTML innerText property of node element. Once the question is set, we are setting the options using the same method discussed in the table. we are also setting the option “value” which is also coming from the array  “Questions”. This “op1.value” means the value for that option button and “Questions[id].a[0].isCorrect” will set it to true or false. Then we are setting one variable “selected” which is used to hold the value for the selected option by the user.
The evaluate button is implemented using the addEventListener function. If it is correct then it will set the “result” div text to “true” and will set the “style.color” property to “green” else it will set the “result” div to “false” and will set the  “style.color” property to “red”. 
We are getting the next button using the class name. The click event is set which will check the id variable. If it is less than our total questions id which is (0,1,2) in our case so that our array does not get out of bound. We are calling the “iterate” function conditionally passing the new id of the question also setting the “start” to false indicating that this is not the start of the quiz.
script.js
// Questions will be askedconst Questions = [{        id: 0,        q: "What is capital of India?",        a: [{ text: "gandhinagar", isCorrect: false },            { text: "Surat", isCorrect: false },            { text: "Delhi", isCorrect: true },            { text: "mumbai", isCorrect: false }        ]      },    {        id: 1,        q: "What is the capital of Thailand?",        a: [{ text: "Lampang", isCorrect: false, isSelected: false },            { text: "phuket", isCorrect: false },            { text: "Ayutthaya", isCorrect: false },            { text: "Bangkok", isCorrect: true }        ]      },    {        id: 2,        q: "What is the capital of Gujarat",        a: [{ text: "surat", isCorrect: false },            { text: "vadodara", isCorrect: false },            { text: "gandhinagar", isCorrect: true },            { text: "rajkot", isCorrect: false }        ]      }  ]  // Set startvar start = true;  // Iteratefunction iterate(id) {      // Getting the result display section    var result = document.getElementsByClassName("result");    result[0].innerText = "";      // Getting the question    const question = document.getElementById("question");        // Setting the question text    question.innerText = Questions[id].q;      // Getting the options    const op1 = document.getElementById('op1');    const op2 = document.getElementById('op2');    const op3 = document.getElementById('op3');    const op4 = document.getElementById('op4');        // Providing option text     op1.innerText = Questions[id].a[0].text;    op2.innerText = Questions[id].a[1].text;    op3.innerText = Questions[id].a[2].text;    op4.innerText = Questions[id].a[3].text;      // Providing the true or false value to the options    op1.value = Questions[id].a[0].isCorrect;    op2.value = Questions[id].a[1].isCorrect;    op3.value = Questions[id].a[2].isCorrect;    op4.value = Questions[id].a[3].isCorrect;      var selected = "";      // Show selection for op1    op1.addEventListener("click", () => {        op1.style.backgroundColor = "lightgoldenrodyellow";        op2.style.backgroundColor = "lightskyblue";        op3.style.backgroundColor = "lightskyblue";        op4.style.backgroundColor = "lightskyblue";        selected = op1.value;    })      // Show selection for op2    op2.addEventListener("click", () => {        op1.style.backgroundColor = "lightskyblue";        op2.style.backgroundColor = "lightgoldenrodyellow";        op3.style.backgroundColor = "lightskyblue";        op4.style.backgroundColor = "lightskyblue";        selected = op2.value;    })      // Show selection for op3    op3.addEventListener("click", () => {        op1.style.backgroundColor = "lightskyblue";        op2.style.backgroundColor = "lightskyblue";        op3.style.backgroundColor = "lightgoldenrodyellow";        op4.style.backgroundColor = "lightskyblue";        selected = op3.value;    })      // Show selection for op4    op4.addEventListener("click", () => {        op1.style.backgroundColor = "lightskyblue";        op2.style.backgroundColor = "lightskyblue";        op3.style.backgroundColor = "lightskyblue";        op4.style.backgroundColor = "lightgoldenrodyellow";        selected = op4.value;    })      // Grabbing the evaluate button    const evaluate = document.getElementsByClassName("evaluate");      // Evaluate method    evaluate[0].addEventListener("click", () => {        if (selected == "true") {            result[0].innerHTML = "True";            result[0].style.color = "green";        } else {            result[0].innerHTML = "False";            result[0].style.color = "red";        }    })}  if (start) {    iterate("0");}  // Next button and methodconst next = document.getElementsByClassName('next')[0];var id = 0;  next.addEventListener("click", () => {    start = false;    if (id < 2) {        id++;        iterate(id);        console.log(id);    }  })
Output:
JavaScript quiz
This was the simple Quiz web App using JavaScript, you can surely take it to the next level by implementing it with your real API, Question shuffles, setting points for the questions, setting the counter, etc. 
CSS-Properties
CSS-Questions
HTML-Questions
JavaScript-Events
JavaScript-Questions
Picked
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.