Dark CSS

Creating a Quiz App using Html CSS and Javascript

Facebook
Twitter
WhatsApp

Project Preview

Folder Structure:

  • First we will need to create a main folder for our projects
  • Inside it we will need to create 3 main files html, css, and js
  • Then we will need to add css and js files to our html file.

 

Quiz App in Javascript

 

Introduction:

This code creates a Simple Quiz Game using HTML, CSS, and JavaScript. It dynamically displays multiple-choice questions, allows users to select an answer, and moves to the next question when the “Next” button is clicked. At the end of the quiz, it shows the user’s score and a “Play Again” option. The JavaScript logic fetches questions from an array, tracks correct and incorrect answers, and updates the interface accordingly.

 

HTML Code:

...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Quiz Game | JavaScript</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h2>Simple Quiz Game</h2>
        <hr>
        <div class="wrapper" id="box">
            <h2 id="quiz">01) What's going on?</h2>

            <div class="row">
                <input class="answers" type="radio" name="radio" id="option1" value="a">
                <label for="option1">Option 1</label>
            </div>

            <div class="row">
                <input class="answers" type="radio" name="radio" id="option2" value="b">
                <label for="option2">Option 2</label>
            </div>

            <div class="row">
                <input class="answers" type="radio" name="radio" id="option3" value="c">
                <label for="option3">Option 3</label>
            </div>

            <div class="row">
                <input class="answers" type="radio" name="radio" id="option4" value="d">
                <label for="option4">Option 4</label>
            </div>

            <button onclick="submitQuiz();">Next</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

...

Explanation:

The HTML structure of this quiz game consists of a container that holds all quiz elements.

Inside this container, there is a heading that displays the quiz title and a horizontal line for separation.

A wrapper div contains the question text and multiple answer options, each represented as a radio button with an associated label. The radio buttons allow users to select only one option at a time.

Below the options, a Next button is placed, which, when clicked, triggers a JavaScript function to check the answer and load the next question.

Finally, an external CSS file is linked in the <head> section to style the quiz, and a JavaScript file is linked at the end to add interactive functionality, such as tracking the user’s answers and displaying the final score.

 

CSS Code:

...
@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: "Poppins", serif;
}

html,
body {
    display: grid;
    height: 100%;
    place-items: center;
    background: #ecf0f1;
}

.container {
    width: 400px;
    background: inherit;
    border-radius: 7px;
    padding: 20px;
    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.115);
}

.container>h2 {
    color: #be2edd;
    font-size: 1rem;
    text-align: center;
}

.container hr {
    margin: 15px 0px;
}

.wrapper h2 {
    margin-bottom: 22px;
    margin-left: 12px;
    font-weight: 600;
    font-size: .9rem;
}

.row {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 10px 0px;
    border-radius: 4px;
    cursor: pointer;
    overflow: hidden;
    background: #f9f9f9;
}

.answers {
    display: none;
}

label {
    width: 100%;
    height: 100%;
    padding: 15px;
    padding-left: 20px;
    font-size: 13px;
    transition: .1s;
    cursor: pointer;
}

.row label:hover {
    background: #dff9fb;
}

.answers:checked+label {
    background: #d6fbfd;
}

button,
a {
    border: 0;
    outline: none;
    padding: 12px;
    width: 100%;
    letter-spacing: 1px;
    text-transform: uppercase;
    margin-top: 20px;
    border-radius: 5px;
    color: #fff;
    background: #be2edd;
    cursor: pointer;
    font-size: 14px;
    transition: background 0.2s;
}

a {
    text-decoration: none;
    display: flex;
    justify-content: center;
    align-items: center;
}

button:hover,
a:hover {
    background: #bd2edddf;
}

h3 {
    font-size: 1rem;
    text-align: center;
    font-size: 600;
    margin: 15px 0px;
}

span {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
}
...

 

Explanation:

It begins by importing the Poppins font from Google Fonts to give the text a modern and clean look. To ensure consistency, all elements have their default padding and margins removed, and a box-sizing property is applied to maintain proper spacing.

The body and HTML are styled to center the quiz in the middle of the screen using a grid layout, while a light gray background provides a subtle contrast to the content.

The quiz container is designed with a compact width, rounded corners, and a slight shadow effect to make it stand out. The title is centered and given a vibrant purple color to grab attention.

The question section is neatly spaced with a slightly bold font, making it easy to read. Each answer option is placed inside a flexbox container to ensure proper alignment.

The background color of the answer options is kept light, and a hover effect is applied to enhance user interactivity.

The default radio buttons are hidden and replaced with custom-styled labels that change color when selected, providing clear visual feedback.

The “Next” button is styled with a bold purple background, uppercase text, and smooth rounded edges, making it easy to interact with. On hover, the button slightly darkens, giving it a more dynamic feel.

JavaScript Code:

....
....

const questions = [
  {
    que: "What does HTML stands for?",
    a: "Hyperlinks and Text Markup Language",
    b: "Hyper Text Markup Language",
    c: "Home Tool Markup Language",
    d: "Hyper Tool Makeup Laguage",
    correct: "b",
  },

  {
    que: "Choose the correct HTML tag for the largest heading",
    a: "<heading>",
    b: "<h6>",
    c: "<head>",
    d: "<h1>",
    correct: "d",
  },

  {
    que: "What is the correct HTML tag for inserting a line break?",
    a: "<br>",
    b: "<lb>",
    c: "</break>",
    d: "<hr>",
    correct: "a",
  },

  {
    que: "What does CSS stand for?",
    a: "Creative Style Sheets",
    b: "Cascading Style Sheets",
    c: "Computer Style Sheets",
    d: "Colorful Style Sheets",
    correct: "b",
  },

  {
    que: "Inside which HTML element do we put the JavaScript?",
    a: "<js>",
    b: "<script>",
    c: "<scripting>",
    d: "<javascript>",
    correct: "b",
  },
];

let index = 0;
let right = 0;
let wrong = 0;
let total = questions.length;
const question = document.querySelector("#quiz");
const ansInput = document.querySelectorAll(".answers");

const getAnswers = () => {
  if (index === total) {
    return result();
  }

  reset();
  let data = questions[index];
  question.innerText = `0${[index + 1]}) ${data.que}`;

  ansInput[0].nextElementSibling.innerText = data.a;
  ansInput[1].nextElementSibling.innerText = data.b;
  ansInput[2].nextElementSibling.innerText = data.c;
  ansInput[3].nextElementSibling.innerText = data.d;
};

const submitQuiz = () => {
  let data = questions[index];
  let ans = matchAns();

  if (ans === data.correct) {
    right++;
  } else {
    wrong++;
  }

  ansInput.forEach((input) => {
    if (input.checked) {
      index++;
      getAnswers();
      return;
    }
  });
};

const matchAns = () => {
  let answers;
  ansInput.forEach((input) => {
    if (input.checked) {
      answers = input.value;
    }
  });

  return answers;
};

const result = () => {
  document.getElementById("box").innerHTML = `<h3>Thanks for playing quiz</h3>
   <span>You scored ${right} / ${total}</span>
   <a href=''>Play Again</a>
  `;
};

const reset = () => {
  ansInput.forEach((input) => {
    input.checked = false;
  });
};

getAnswers();

...

Explanations:

The JavaScript code for the quiz game dynamically manages the questions, validates answers, and displays the final score.

It begins by storing the quiz questions in an array of objects, where each object contains a question, four answer options, and the correct answer.

Variables track the current question index, the number of correct answers, and incorrect attempts. The script selects key elements from the DOM, such as the question container and answer options, and updates them dynamically.

The getAnswers function loads a new question by updating the text and options, ensuring the quiz progresses smoothly.

When the user selects an answer and clicks “Next,” the submitQuiz function checks whether the selected option matches the correct answer and updates the score accordingly.

The matchAns function helps retrieve the selected answer, while the reset function ensures that no previous answer remains checked when a new question loads.

Once all questions are answered, the result function replaces the quiz interface with a final message displaying the user’s score and a “Play Again” option. The script initializes by calling getAnswers, ensuring the first question appears when the game starts.

This JavaScript logic ensures a seamless and interactive quiz experience by handling navigation, answer validation, and result display efficiently.

Source Code:

Download “Quiz-Game.7z” Quiz-Game.7z – Downloaded 61 times – 2.15 KB

Conclusions:

In this project, we built a simple quiz game using HTML, CSS, and JavaScript.  The JavaScript handled quiz functionality, dynamically updating questions, checking user responses, and displaying the final score. We used an array to store quiz questions and iterated through them as the user progressed. Answer validation ensured that correct and incorrect responses were recorded accurately. The quiz automatically resets answers before loading the next question to avoid selection errors. Once all questions are answered, the user receives a final score with an option to replay. This interactive quiz showcases how javaScript can be used to create dynamic and engaging web applications.