Open In App

Create a Quiz Application Using JavaScript

Last Updated : 07 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to create a quiz application using JavaScript. The quiz application will contain questions followed by a total score shown at the end of the quiz. The score will increase based on the correct answers given. Initially, there are only three questions but you can increase the questions in the JavaScript file.

We will create the structure using HTML and design it with CSS. JavaScript will be used to implement the logic and scoring of the quiz.

Preview:

Prerequisites:

Approach:

  • Create a project workspace with three different files for HTML, CSS and JavaScript. In the HTML file, the structure of the quiz application will be defined using different HTML tags like div, paragraph, heading, buttons, etc.
  • The second file will be for CSS, In which the HTML elements will be grabbed using their IDs and Classes and styled accordingly with the help of CSS properties.
  • Now, the final file will be created for JavaScript. In this file, the whole logic of our quiz application will be defined by grabbing the elements with the help of DOM.
  • Next, an API will be called using the fetch method with some callback functions to manage the fetched data into different states like loading, failed, and success.
  • The button element will be grabbed and click event will be added to it, so that it loads the next quetion on the user screen once user clicks it.

Example: The below example will illustrate you the code structure of the whole project:

Javascript




let Questions = [];
const ques = document.getElementById("ques")
 
async function fetchQuestions() {
    try {
        const response = await
         fetch('https://opentdb.com/api.php?amount=10');
        if (!response.ok) {
            throw new Error(`Something went wrong!!
        Unable to fecth the data`);
        }
        const data = await response.json();
        Questions = data.results;
    }
    catch (error) {
        console.log(error);
        ques.innerHTML = `<h5 style='color: red'>
        ${error}</h5>`;
    }
}
fetchQuestions();
 
let currQuestion = 0
let score = 0
 
if (Questions.length === 0) {
    ques.innerHTML = `<h5>Please Wait!!
    Loading Questions...</h5>`
}
 
function loadQues() {
    const opt = document.getElementById("opt");
    let currentQuestion = Questions[currQuestion].question;
    if (currentQuestion.indexOf('"') > -1) {
        currentQuestion = currentQuestion
            .replace(/"/g, '\"');
    }
    if (currentQuestion.indexOf(''') > -1) {
        currentQuestion = currentQuestion
            .replace(/&#039;/g, '\'');
    }
    ques.innerText = currentQuestion;
    opt.innerHTML = ""
    const correctAnswer = Questions[currQuestion]
        .correct_answer;
    console.log(Questions);
    const incorrectAnswers = Questions[currQuestion]
        .incorrect_answers;
    const options = [correctAnswer, ...incorrectAnswers];
    options.sort(() => Math.random() - 0.5);
    options.forEach((option) => {
        if (option.indexOf('"') > -1) {
            option = option.replace(/"/g, '\"');
        }
        if (option.indexOf(''') > -1) {
            option = option.replace(/'/g, '\'');
        }
        const choicesdiv = document.createElement("div");
        const choice = document.createElement("input");
        const choiceLabel = document.createElement("label");
        choice.type = "radio";
        choice.name = "answer";
        choice.value = option;
        choiceLabel.textContent = option;
        choicesdiv.appendChild(choice);
        choicesdiv.appendChild(choiceLabel);
        opt.appendChild(choicesdiv);
    });
}
 
setTimeout(() => {
    loadQues();
    if (Questions.length === 0) {
        ques.innerHTML = `<h5 style='color: red'>Unable
        to fetch data, Please try again!!</h5>`
    }
}, 2000)
 
 
function loadScore() {
    const totalScore = document.getElementById("score");
    totalScore.textContent = `You scored ${score} out
    of ${Questions.length}`;
    totalScore.innerHTML += "<h3>All Answers</h3>"
    Questions.forEach((el, index) => {
        totalScore.innerHTML += `<p>${index + 1}.
         ${el.correct_answer}</p>`
    })
}
 
 
function nextQuestion() {
    if (currQuestion < Questions.length - 1) {
        currQuestion++;
        loadQues();
    } else {
        document.getElementById("opt").remove()
        document.getElementById("ques").remove()
        document.getElementById("btn").remove()
        loadScore();
    }
}
 
function checkAns() {
    const selectedAns = document.
        querySelector('input[name="answer"]:checked').value;
 
    if (selectedAns === Questions[currQuestion].correct_answer) {
        score++;
        nextQuestion();
    } else {
        nextQuestion();
    }
}


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">
        <h1>Quiz Application Using JavaScript</h1>
        <div class="question" id="ques"></div>
        <div class="options" id="opt"></div>
        <button onclick="checkAns()" id="btn">SUBMIT</button>
        <div id="score"></div>
        <script src="script.js"></script>
    </div>
 
</body>
 
</html>


CSS




body {
    background-color: aliceblue;
}
 
.panel {
    margin-top: 8%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: navy;
}
 
.question {
    text-align: center;
    font-size: 30px;
    width: 50%;
    margin-bottom: 20px;
}
 
.options {
    font-size: 20px;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 20px;
    margin-top: 10px;
    margin-bottom: 20px;
}
 
button {
    margin-right: 75px;
    margin-top: 8%;
    font-size: 20px;
    padding: 10px 20px;
    background-color: #4f98c2;
    color: white;
    border: none;
    cursor: pointer;
}
 
button:hover {
    color: #4f98c2;
    background-color: white;
    border: 1 px solid #4f98c2;
}
 
#score {
    font-size: 30px;
    color: darkslategray;
}


Output:
QuizAppGif

Note: 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. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads