Interactive Quiz Project in JavaScript

In this blog, we’ll be eying to create an interactive quiz using JavaScript, HTML and CSS.

First things first we need to set up our HTML document for our Interactive quiz and we’ll try to keep it as minimal as possible.

Setting our HTML:

So let’s set our HTML to be:

<h1>Interactive Quiz</h1>
<div id="scores"></div>
<div id="quiz-skeleton">H</div>
<button id="submit">Submit Quiz</button>

Setting our Javascript:

We can access these div elements in our Javascript via our defined ID’s.

You can also read: Guess The Number Game Using JavaScript

Now, we’ll need a basic structure of our JavaScript, we can start by seeing what functions we’ll need and fill them as we go. So the basic structure is something like this,

// Variables
const quiz = document.getElementById('quiz-skeleton');
const results = document.getElementById('scores');
const submit = document.getElementById('submit');
const Questions = [ ... ];

// Functions
function startquiz(){ ... }
function showResults(){ ... }

// Dispay the quiz
startquiz();

// Validation of the Answers
submit.addEventListener('click', showResults)

The next thing that we need to do is set up our question in a Javascript Object(JSON) so that we can access or send it in a database if ever need be. For the purpose of this tutorial we would just keep it in out Javascript file.

const questions = [
    {
        question: "What is the speed of light?",
        answer: {
            a: "3 * 10^8",
            b: "2 * 10^6",
            c: "3 * 10^7"
        },
        correctAns: "a"

    },
    {
        question: "What does the square of a Schrodinger wave function represent?",
        answer: {
            a: "Energy",
            b: "Probability",
            c: "Momentum"
        },
        correctAns: "b"

    },
    {
        question: "Who is the creator of this quiz?",
        answer: {
            a: "Saksham Agarwal",
            b: "Donald Duck",
            c: "Dora the explorer"
        },
        correctAns: "a"
    }
]

Displaying the quiz :

You can put many more questions if need be but right now we’ll be using these 3 questions. Now let’s discuss on the buildQuiz() function which would be used to display the quiz questions.

function StartQuiz()
{
    //Variable to store the Code that would be appended to HTML.
    const HtmlCode = [];

    questions.forEach((currQuestion,QuestionNumber) =>  {
        //An array to store all the possible answers
        var AllAnswers = []

        for(index in currQuestion.answer) {
            //Now we need to push the HTML code into our AllAnswers 
            //which would be used to display these answers
            //I have given a name to the radio button as it makes 
            //easier to access it if needed
            AllAnswers.push(
                `<p>
                    <input type="radio" name="Q${QuestionNumber + 1}" value="${index}">
                    ${index} : 
                    ${currQuestion.answer[index]}
                </p>`
            );
        }

        HtmlCode.push(
            `
            <div class="question">${currQuestion.question}</div>
            <div class="answers">${AllAnswers.join('')}</div>
            `
        );
    });
    console.log(HtmlCode);
    console.log(divquiz.innerHTML)
    divquiz.innerHTML = HtmlCode.join('');
}

So let’s go through the code step by step.

Steps:

  • We created an HtmlCode array which would store the code that is to be added to display the quiz.
  • After that, we traverse into our question JSON and create a code for HTML code for the MSQ answers and append it into our answers list.
  • Finally, we package each question and its corresponding MCQ in div and add it to inside the div ‘quiz-skeleton’.

Note: We are using some concepts like string interpolation here i.e to add Javascript variable to some expressions you can use something like ${something_added_here}.

  • If you call this code you should be able to see your quiz questions and MCQ options.

Validation of our quiz and scores using JavaScript

Now we need to loop our questions and compare the user answer with our correct answer to see how many of these answers are correct.

function ShowResults()
{
    //Getting a NOde list of all the answer elements in out HTML code
    const divanswers = divquiz.querySelectorAll('.answers');

    //Variable to store the number of correc answers
    var No_correctAns = 0;

    //Running again for all the questions
    questions.forEach((currQuestion,QuestionNumber) => {

        var currAnsContainer = divanswers[QuestionNumber];
        var correctAns = currQuestion.correctAns
        var property = `input[name=Q${QuestionNumber + 1}]:checked`;
        var UserAns = (currAnsContainer.querySelector(property) || {}).value

        if(UserAns == correctAns)
        {
            No_correctAns += 1;
            divanswers[QuestionNumber].style.color = "green";
        } 
        else
        {
            divanswers[QuestionNumber].style.color = "red";
        }
    });

    if(No_correctAns == 0)
        divresult.style.color = "red"
    if(No_correctAns == 1)
        divresult.style.color = "orange"
    if(No_correctAns == 2)
        divresult.style.color = "blue"
    if(No_correctAns == 3)
        divresult.style.color = "green"
    
    divresult.innerHTML = `Scores : ${No_correctAns} out of ${questions.length}`;
}

Steps:

  • Here we are using queryselectorAll() to get all the answer fields in our HTML document. After this, we will use querySelector() with our selector being all the input fields that have been checked. These are the answers that have been chosen by the user.
  • We loop through all the questions and compare the UserAnswer with the correct answer and change the color of all the MCQ fields, green if correct and red if incorrect.
  • Here we are also storing the number of correct answers that are finally returned and stored inside the results div. We also choose the answer for this div according to the number of correct answers.

Note:

var UserAns = (currAnsContainer.querySelector(property) || {}).value

Here I have used “|| {}” this expression as if the user has left some question empty then the queryselector() gives an error and thus to handle that error we choose an empty Node as a solution.

You can check out the result of this Interactive quiz at:

https://codepen.io/Dragonsa15/pen/OJyBeKR

Leave a Reply

Your email address will not be published.