Create a simple JavaScript quiz

How to create a simple JavaScript quiz?

JavaScript is useful for making any webpage dynamic. In this article, we are going to see how to create a simple Quiz web application using JavaScript.

This Quiz web app will have the following features.

A user interfaces for the question and four interactive options. Navigation between questions. Evaluation as 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 identifiers to identify them. The names of classes and ids are chosen such that they carry 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 to hold the question text and display them. The third "div" is for "option-container" as the name suggests, it will contain the four options for the question. The fourth “div” is for “navigation” which will have a button to navigate to the next question and to rate the selected answer.

All these four “div” are also inside another “div” with a class “panel”. We use this DOM element in our script.

Example:

So let's go to our HTML code: The following code illustrates 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: CSS helps align different options and buttons.

Firstly, let's talk about the hover property. it is responsible for creating the selection effect of the option. We will also modify the selection effect using JavaScript.

Also, the code takes care of the appearance and alignment of the user interface. The file is included in the head section of the code above.

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 will equally have to dynamically display the question and the options, for this we have created an array of objects, in which each object has a question and the corresponding options and the information of the correct answer. With this array of objects, we have the JSON format so it helps us to handle the API and handle the actual data which is of JSON type most of the time.

Let's see how we can access different things from this “Questions” array:

How to access any question text Questions[id].q How to access the text of the first option of any question Question[id].a[0].text How to know if the option is true or false Questions[id].a[0].isCorrect

Note:

Firstly, the "id" keeps changing depending on the question number, it represents the question number of the array.

In addition, the Questions array is also defined. We took a boolean variable "start" which is initially set to true which will also indicate the start of the Quiz. The iterate() function is equally 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.

So let's see how the iterate() function works:

We get the result of the HTML div and set it to empty text using the HTML innerText property of the node element. Once the question is defined, we also define the options using the same method described in the array. we also define the “value” option which also comes from the “Questions” array. This "op1.value" means the value of this option button and "Questions[id].a[0].isCorrect" will set it to true or false . Next, we define a “selected” variable which is used to hold the value of the option selected by the user.

The rating button is equally implemented using the addEventListener function. If it is correct it will set the text div 'result' to 'true' and set the property 'style. color' to 'green', otherwise it will set the div 'result' to 'false' and set the 'style. color” property to “red”.

We also get the following button using the class name. The click event is set, which will check the id variable. If it is less than the total of our questions, id which is (0,1,2) in our case so that our array does not go out of bounds. We call the 'iterate' function conditionally passing the new question id and also setting the 'start' to false indicating that this is not the start of the quiz.

Create a simple Quiz web application using JavaScript script.js

// Questions will be asked
const Questions = [{
    id: 0,
    q: "Who was the fourth president of the United States?",
    a: [{ text: "Abraham Lincoln", isCorrect: false },
        { text: "James Madison", isCorrect: false },
        { text: "George Washington", isCorrect: true },
        { text: "Alexander Hamilton", isCorrect: false }
    ]

},
{
    id: 1,
    q: "What is the name of the longest river in Africa?",
    a: [{ text: "Lampang", isCorrect: false, isSelected: false },
        { text: "Mississippi River", isCorrect: false },
        { text: "River Congo", isCorrect: false },
        { text: "Nile River", isCorrect: true }
    ]

},
{
    id: 2,
    q: " What is the diameter of a basketball hoop in inches?",
    a: [{ text: "28 inches", isCorrect: false },
        { text: "08 inches", isCorrect: false },
        { text: "18 inches", isCorrect: true },
        { text: "38 inches", isCorrect: false }
    ]

}

]

// Set start
var start = true;

// Iterate
function 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 method
const next = document.getElementsByClassName('next')[0];
var id = 0;

next.addEventListener("click", () => {
start = false;
if (id < 2) {
    id++;
    iterate(id);
    console.log(id);
}

})