Build A Quiz App with Timer in HTML CSS & JavaScript

0

Build Quiz App with Timer in HTML CSS & JavaScript

In today’s fast-paced digital world, everyone loves a good quiz! Whether it’s for testing your knowledge on a specific topic, challenging your friends, or just passing the time, quiz apps are a fun and engaging way to learn and compete. If you’ve ever wanted to create your own interactive quiz app, you’re in the right place!

In this blog post, I’ll guide you through how to build a simple yet dynamic quiz app with a timer using HTML, CSS, and JavaScript. This app allows users to choose their preferred quiz category and the number of questions. Each question has four possible answers and a 15-second timer. Once users complete the quiz, they can see their score and have the option to try again.

Why Should You Create a Quiz App?

Creating a Quiz App with a Timer using HTML, CSS, and JavaScript is more than just a fun project. It’s a great way to build valuable skills and here’s what you’ll learn:

  • Practice Core Skills: Strengthen your HTML, CSS, and JavaScript knowledge with fun and practical projects.
  • Learn Event Handling: Get hands-on experience working with timers, user input, and dynamic content.
  • Enhance User Interaction: Improve your UX design skills with interactive features like quiz categories and a scoring system.
  • Boost Problem-Solving: Learn how to structure your app logically and manage quiz flow effectively.
  • Create a Portfolio Piece: Build a simple yet impressive project to showcase in your portfolio.

Video Tutorial of Quiz App in HTML CSS & JavaScript

The YouTube tutorial above is an excellent resource if you prefer video learning. It covers every line of code in detail, with helpful comments to make the process easy to follow. For those who prefer a written guide, keep reading as we break down each step of the quiz project.

Steps to Create Quiz App in HTML CSS & JavaScript

To create an interactive quiz app with a timer using HTML, CSS, and JavaScript, follow these simple step-by-step instructions:

  • Create a folder with any name you like, e.g., quiz-app.
  • Inside it, create the following files: index.html, style.css, and a javascript folder with questions.js and script.js files.
  • Download the quiz-over.png image and place it in your project directory.

In your index.html file, start by setting up the basic HTML structure for the quiz app project. This includes the container for the configuration (where users select their quiz settings), the quiz itself (with questions and answers), and the result section (where users will see their scores).

<!DOCTYPE html>
<!-- Coding By CodingNepal - youtube.com/@codingnepal -->
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Quiz App in JavaScript | CodingNepal</title>
    <!-- Linking Google fonts for icons -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@24,400,0,0" />
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <!-- Quiz Configuration Container -->
    <div class="config-container">
      <h2 class="config-title">Quiz Configuration</h2>

      <div class="config-option">
        <h4 class="option-title">Select Category</h4>
        <div class="category-options">
          <button class="category-option active">Programming</button>
          <button class="category-option">Geography</button>
          <button class="category-option">Mathematics</button>
          <button class="category-option">Entertainment</button>
        </div>
      </div>

      <div class="config-option">
        <h4 class="option-title">No. of Questions</h4>
        <div class="question-options">
          <button class="question-option">5</button>
          <button class="question-option active">10</button>
          <button class="question-option">15</button>
          <button class="question-option">20</button>
          <button class="question-option">25</button>
        </div>
      </div>

      <button class="start-quiz-btn">Start Quiz</button>
    </div>

    <!-- Quiz Container -->
    <div class="quiz-container">
      <header class="quiz-header">
        <h2 class="quiz-title">Quiz Application</h2>
        <div class="quiz-timer">
          <span class="material-symbols-rounded">timer</span>
          <p class="timer-duration"></p>
        </div>
      </header>

      <div class="quiz-content">
        <h1 class="question-text"></h1>
        <ul class="answer-options"></ul>
      </div>

      <div class="quiz-footer">
        <p class="question-status"></p>
        <button class="next-question-btn">
          Next
          <span class="material-symbols-rounded">arrow_right_alt</span>
        </button>
      </div>
    </div>

    <!-- Quiz Result Container -->
    <div class="result-container">
      <img src="quiz-over.png" class="result-img" />
      <h2 class="result-title">Quiz Completed!</h2>
      <p class="result-message"></p>
      <button class="try-again-btn">Try Again</button>
    </div>

    <script src="javascript/questions.js"></script>
    <script src="javascript/script.js"></script>
  </body>
</html>

In your style.css file, style your quiz app to achieve a sleek, modern, and responsive design. Feel free to experiment with different colors, fonts, and layout styles to give it a personal touch.

/* Importing Google fonts - Montserrat */
@import url('https://fonts.googleapis.com/css2?family=Montserrat:[email protected]&display=swap');

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

body {
  display: flex;
  padding: 15px;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background: #5145BA;
}

:where(.config-container, .quiz-container, .result-container) {
  display: none;
  background: #fff;
  border-radius: 9px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.13);
}

/* Quiz Configuration Stylings */
.config-container {
  display: block;
  width: 415px;
  padding: 25px;
  text-align: center;
}

.config-container .config-title {
  font-size: 1.31rem;
}

.config-container .config-option {
  margin-top: 25px;
}

.config-option .option-title {
  font-weight: 500;
  font-size: 1.125rem;
  margin-bottom: 20px;
}

.config-option .category-options {
  display: grid;
  gap: 15px;
  grid-template-columns: repeat(2, 1fr);
}

.config-option .question-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 0 30px;
  justify-content: center;
}

.config-option button {
  padding: 12px;
  font-size: 0.938rem;
  color: #000;
  cursor: pointer;
  font-weight: 500;
  border-radius: 7px;
  background: #fff;
  border: 1px solid #9B8FFF;
  transition: 0.3s ease;
}

.config-option button.active {
  color: #5145BA;
  border-color: #5145BA;
  background: #dfdafd;
}

.config-option button:hover,
.quiz-content .answer-option:hover {
  background: #dad5fd;
}

.config-option .question-options button {
  flex: 1 1 10%;
}

.config-container .start-quiz-btn,
.quiz-footer .next-question-btn,
.result-container .try-again-btn {
  color: #fff;
  border: none;
  font-weight: 500;
  background: #5145BA;
  padding: 13px 25px;
  cursor: pointer;
  font-size: 1rem;
  border-radius: 7px;
  transition: background 0.3s ease;
}

.config-container .start-quiz-btn {
  margin-top: 30px;
}

.config-container .start-quiz-btn:hover,
.quiz-footer .next-question-btn:hover,
.result-container .try-again-btn:hover {
  background: #403795;
}

/* Quiz Container Stylings */
.quiz-container {
  width: 480px;
}

.quiz-container .quiz-header {
  display: flex;
  padding: 14px 25px;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.09);
}

.quiz-header .quiz-title {
  font-size: 1.43rem;
  font-weight: 700;
}

.quiz-header .quiz-timer {
  display: flex;
  width: 70px;
  color: #fff;
  gap: 5px;
  align-items: center;
  background: #32313C;
  border-radius: 7px;
  padding: 7px 9px;
  font-weight: 600;
  transition: 0.2s ease;
}

.quiz-header .quiz-timer span {
  font-size: 1.4rem;
}

.quiz-container .quiz-content {
  padding: 20px 25px 25px;
}

.quiz-content .question-text {
  font-size: 1.5rem;
  font-weight: 600;
}

.quiz-content .answer-options {
  list-style: none;
  display: flex;
  gap: 15px;
  margin-top: 20px;
  flex-direction: column;
}

.quiz-content .answer-option {
  display: flex;
  cursor: pointer;
  align-items: center;
  font-weight: 500;
  border-radius: 7px;
  padding: 13px 16px;
  border: 1px solid #B5ACFF;
  background: #F3F1FF;
  justify-content: space-between;
  transition: 0.3s ease;
}

.quiz-content .answer-option span {
  display: block;
  flex-shrink: 0;
  margin: -4px -3px -4px 12px;
}

.quiz-content .answer-option.correct {
  border-color: #B7E1C1;
  background: #D4EDDA;
  color: #155724;
}

.quiz-content .answer-option.correct span {
  color: #16AE56;
}

.quiz-content .answer-option.incorrect {
  border-color: #F4BEC3;
  background: #F8D7DA;
  color: #721C24;
}

.quiz-content .answer-option.incorrect span {
  color: #F23723;
}

.quiz-container .quiz-footer {
  padding: 15px 25px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-top: 1px solid #C6C6C6;
}

.quiz-footer .question-status {
  font-weight: 500;
}

.quiz-footer .question-status b,
.result-container .result-message b {
  font-weight: 600;
}

.quiz-footer .next-question-btn {
  display: inline-flex;
  gap: 5px;
  align-items: center;
  padding: 9px 17px;
}

/* Quiz Result Stylings */
.result-container {
  text-align: center;
  padding: 40px;
  width: 410px;
}

.result-container .result-img {
  width: 110px;
}

.result-container .result-title {
  margin-top: 30px;
}

.result-container .result-message {
  font-size: 1.125rem;
  font-weight: 500;
  margin-top: 15px;
}

.result-container .try-again-btn {
  padding: 12px 20px;
  margin-top: 30px;
}

/* Media query code for mobile screens */
@media (max-width: 624px) {

  .config-container,
  .quiz-container .quiz-content {
    padding: 20px;
  }

  .quiz-content .answer-option {
    padding: 12px 10px 12px 14px;
  }

  .config-container .question-options {
    padding: 0 15px;
  }

  .quiz-container .quiz-header,
  .quiz-container .quiz-footer {
    padding: 13px 20px;
  }

  .quiz-header .quiz-title,
  .quiz-content .question-text {
    font-size: 1.3rem;
  }

  .result-container {
    padding: 40px 20px;
  }

  .result-container .result-title {
    font-size: 1.4rem;
  }
}

In your javascript/questions.js file, add the following quiz data. This includes the quiz categories, questions, answer options, and the correct answer for each one. You can easily update or add the questions in this file.

// Array of questions grouped by category (25 questions each)

const questions = [
  {
    category: "programming",
    questions: [
      {
        question: "What does HTML stand for?",
        options: ["Hyper Text Pre Processor", "Hyper Text Markup Language", "Hyper Text Multiple Language", "Hyper Tool Multi Language"],
        correctAnswer: 1,
      },
      {
        question: "Which of the following is a correct way to declare a variable in JavaScript?",
        options: ["var x = 10;", "variable x = 10;", "int x = 10;", "let 10 = x;"],
        correctAnswer: 0,
      },
      {
        question: "How do you write comment in Python?",
        options: ["// This is a comment", "# This is a comment", "/* This is a comment */", "<!-- This is a comment -->"],
        correctAnswer: 1,
      },
      {
        question: "What does CSS stand for?",
        options: ["Cascading Style Sheets", "Colorful Style Sheets", "Computer Style Sheets", "Cascading Simple Sheets"],
        correctAnswer: 0,
      },
      {
        question: "In JavaScript, how do you create a function?",
        options: ["create function myFunction()", "def function myFunction()", "func myFunction()", "function myFunction()"],
        correctAnswer: 3,
      },
      {
        question: "What does the 'typeof' operator do in JavaScript?",
        options: ["Checks the type of a variable", "Declares a variable", "Assigns a value to a variable", "Converts a variable to another type"],
        correctAnswer: 0,
      },
      {
        question: "In C, how do you define a function?",
        options: ["function myFunction()", "def myFunction()", "void myFunction()", "func myFunction()"],
        correctAnswer: 2,
      },
      {
        question: "Which of the following is a characteristic of Python?",
        options: ["Compiled language", "Dynamic typing", "Low-level language", "Static typing"],
        correctAnswer: 3,
      },
      {
        question: "Which language is used for Android development?",
        options: ["Python", "Java", "JavaScript", "C++"],
        correctAnswer: 1,
      },
      {
        question: "What is the purpose of the 'forEach()' method in JavaScript?",
        options: ["Removes duplicate elements from an array", "Filters elements in an array", "Sorts an array", "Iterates through each element in an array"],
        correctAnswer: 3,
      },
      {
        question: "What does the 'return' keyword do in a function?",
        options: ["Ends the function and returns a value", "Continues the function", "Exits the function without value", "Ends the program execution"],
        correctAnswer: 0,
      },
      {
        question: "Which of the following is NOT a semantic HTML element?",
        options: ["<header>", "<footer>", "<div>", "<article>"],
        correctAnswer: 2,
      },
      {
        question: "What is the primary purpose of a 'for' loop in programming?",
        options: ["Repeat code for a specified number of times", "Repeat code until a condition is true", "Define a function", "Evaluate conditions in the loop"],
        correctAnswer: 0,
      },
      {
        question: "Which data structure is ideal for LIFO (Last In First Out)?",
        options: ["Queue", "Stack", "Linked list", "Array"],
        correctAnswer: 1,
      },
      {
        question: "Which command is used in Git to store changes in the repository?",
        options: ["git commit", "git push", "git pull", "git add"],
        correctAnswer: 0,
      },
      {
        question: "What does the 'map()' function do in JavaScript?",
        options: ["Sorts an array", "Filters out items", "Creates a new array", "Modifies the original array"],
        correctAnswer: 2,
      },
      {
        question: "What is an IDE?",
        options: ["An Integrated Development Environment", "A function for code execution", "An interpreter", "An input method for writing code"],
        correctAnswer: 0,
      },
      {
        question: "Which of the following is a feature of object-oriented programming?",
        options: ["Encapsulation", "Modularity", "Recursion", "Memory Management"],
        correctAnswer: 0,
      },
      {
        question: "What does SQL stand for?",
        options: ["Simple Question Language", "Systematic Query Language", "Standard Question Language", "Structured Query Language"],
        correctAnswer: 3,
      },
      {
        question: "Which of these is an example of a non-relational database?",
        options: ["MongoDB", "MySQL", "PostgreSQL", "Oracle"],
        correctAnswer: 0,
      },
      {
        question: "How do you write comment in CSS?",
        options: ["// This is a comment", "/* This is a comment */", "# This is a comment", "<!-- This is a comment -->"],
        correctAnswer: 1,
      },
      {
        question: "Which of the following algorithms is used to sort an array by comparing elements?",
        options: ["Bubble sort", "Insertion sort", "Quick sort", "Merge sort"],
        correctAnswer: 0,
      },
      {
        question: "What does the 'finally' block in Java do?",
        options: ["Handles all exceptions", "Attempts to handle runtime exceptions", "Executes code after try-catch", "Defines execution start point"],
        correctAnswer: 2,
      },
      {
        question: "Which data structure is best for searching elements quickly?",
        options: ["Binary search tree", "Array", "Linked list", "Queue"],
        correctAnswer: 0,
      },
      {
        question: "What is the correct syntax for a JavaScript if statement?",
        options: ["if (condition) {}", "if condition {}", "if {} else", "if {condition}"],
        correctAnswer: 0,
      },
    ],
  },

  {
    category: "geography",
    questions: [
      {
        question: "Which is the longest river in the world?",
        options: ["Amazon River", "Nile River", "Yangtze River", "Mississippi River"],
        correctAnswer: 1,
      },
      {
        question: "Which country is known as the Land of the Rising Sun?",
        options: ["China", "South Korea", "Japan", "Thailand"],
        correctAnswer: 2,
      },
      {
        question: "What is the largest ocean in the world?",
        options: ["Atlantic Ocean", "Indian Ocean", "Arctic Ocean", "Pacific Ocean"],
        correctAnswer: 3,
      },
      {
        question: "Which country has the largest population in the world?",
        options: ["India", "China", "United States", "Indonesia"],
        correctAnswer: 1,
      },
      {
        question: "Which country is known for the Great Barrier Reef?",
        options: ["Australia", "United States", "South Africa", "New Zealand"],
        correctAnswer: 0,
      },
      {
        question: "Which is the smallest country in the world?",
        options: ["Monaco", "Liechtenstein", "Vatican City", "San Marino"],
        correctAnswer: 2,
      },
      {
        question: "Which is the tallest mountain in the world?",
        options: ["K2", "Mount Kilimanjaro", "Mount Everest", "Mount Fuji"],
        correctAnswer: 2,
      },
      {
        question: "What is the capital of Canada?",
        options: ["Ottawa", "Toronto", "Vancouver", "Montreal"],
        correctAnswer: 0,
      },
      {
        question: "Which desert is the largest hot desert in the world?",
        options: ["Gobi Desert", "Atacama Desert", "Sahara Desert", "Karakum Desert"],
        correctAnswer: 2,
      },
      {
        question: "Which country is known as the Land of the Midnight Sun?",
        options: ["Sweden", "Finland", "Norway", "Denmark"],
        correctAnswer: 2,
      },
      {
        question: "What is the longest mountain range in the world?",
        options: ["Himalayas", "Rocky Mountains", "Andes", "Alps"],
        correctAnswer: 2,
      },
      {
        question: "Which river flows through Egypt?",
        options: ["Amazon River", "Yangtze River", "Nile River", "Ganges River"],
        correctAnswer: 2,
      },
      {
        question: "Which is the largest island in the world?",
        options: ["Greenland", "New Guinea", "Borneo", "Madagascar"],
        correctAnswer: 0,
      },
      {
        question: "What is the capital of Japan?",
        options: ["Beijing", "Seoul", "Tokyo", "Hong Kong"],
        correctAnswer: 2,
      },
      {
        question: "Which country has the most time zones?",
        options: ["United States", "Russia", "Canada", "Australia"],
        correctAnswer: 1,
      },
      {
        question: "Which country is known for the Eiffel Tower?",
        options: ["Germany", "Italy", "Spain", "France"],
        correctAnswer: 3,
      },
      {
        question: "Which is the most populous city in the world?",
        options: ["Tokyo", "Shanghai", "New York City", "Delhi"],
        correctAnswer: 0,
      },
      {
        question: "Which mountain range is located in South America?",
        options: ["Himalayas", "Rocky Mountains", "Appalachian Mountains", "Andes"],
        correctAnswer: 3,
      },
      {
        question: "Which continent is known as the 'Dark Continent'?",
        options: ["Asia", "Africa", "South America", "Europe"],
        correctAnswer: 1,
      },
      {
        question: "What is the capital of Brazil?",
        options: ["Buenos Aires", "Rio de Janeiro", "Brasília", "Sao Paulo"],
        correctAnswer: 2,
      },
      {
        question: "What is the official language of Brazil?",
        options: ["Spanish", "English", "Portuguese", "French"],
        correctAnswer: 2,
      },
      {
        question: "Which country has the most volcanoes?",
        options: ["Japan", "Indonesia", "United States", "Italy"],
        correctAnswer: 1,
      },
      {
        question: "Which city is known as the Big Apple?",
        options: ["Los Angeles", "New York City", "Chicago", "San Francisco"],
        correctAnswer: 1,
      },
      {
        question: "Which ocean is located to the east of Africa?",
        options: ["Indian Ocean", "Pacific Ocean", "Southern Ocean", "Atlantic Ocean"],
        correctAnswer: 3,
      },
      {
        question: "Which is the second largest continent by area?",
        options: ["Asia", "Africa", "North America", "Europe"],
        correctAnswer: 1,
      },
    ],
  },

  {
    category: "mathematics",
    questions: [
      {
        question: "What is the square root of 144?",
        options: ["10", "11", "12", "13"],
        correctAnswer: 2,
      },
      {
        question: "What is 15 × 13?",
        options: ["180", "185", "195", "200"],
        correctAnswer: 2,
      },
      {
        question: "What is the value of 8³?",
        options: ["512", "216", "256", "128"],
        correctAnswer: 0,
      },
      {
        question: "What is 48 ÷ 6?",
        options: ["7", "8", "9", "10"],
        correctAnswer: 1,
      },
      {
        question: "What is the value of 3 + 5 × 4?",
        options: ["20", "22", "24", "23"],
        correctAnswer: 3,
      },
      {
        question: "What is the sum of the angles in a triangle?",
        options: ["180°", "360°", "90°", "270°"],
        correctAnswer: 0,
      },
      {
        question: "What is the perimeter of a square with a side length of 4 cm?",
        options: ["12 cm", "16 cm", "20 cm", "24 cm"],
        correctAnswer: 1,
      },
      {
        question: "What is 11²?",
        options: ["121", "131", "141", "111"],
        correctAnswer: 3,
      },
      {
        question: "What is 9 × 12?",
        options: ["105", "110", "108", "120"],
        correctAnswer: 2,
      },
      {
        question: "What is the value of 16 ÷ 4?",
        options: ["2", "3", "4", "5"],
        correctAnswer: 2,
      },
      {
        question: "What is 25% of 200?",
        options: ["30", "40", "50", "60"],
        correctAnswer: 2,
      },
      {
        question: "What is the area of a rectangle with length 5 cm and width 8 cm?",
        options: ["40 cm²", "50 cm²", "55 cm²", "60 cm²"],
        correctAnswer: 0,
      },
      {
        question: "What is the value of 10 ÷ 2 + 3?",
        options: ["8", "7", "9", "6"],
        correctAnswer: 1,
      },
      {
        question: "What is 3 × 7 + 2?",
        options: ["20", "21", "22", "23"],
        correctAnswer: 1,
      },
      {
        question: "What is the greatest common divisor (GCD) of 24 and 36?",
        options: ["4", "6", "8", "12"],
        correctAnswer: 3,
      },
      {
        question: "What is the least common multiple (LCM) of 6 and 8?",
        options: ["24", "32", "48", "56"],
        correctAnswer: 0,
      },
      {
        question: "What is the value of 2³ × 3?",
        options: ["12", "15", "18", "24"],
        correctAnswer: 0,
      },
      {
        question: "What is the value of 10 × (5 + 3)?",
        options: ["80", "70", "60", "50"],
        correctAnswer: 1,
      },
      {
        question: "What is the value of 14 × 14?",
        options: ["186", "196", "206", "216"],
        correctAnswer: 1,
      },
      {
        question: "What is the sum of the first 10 positive integers?",
        options: ["50", "55", "60", "65"],
        correctAnswer: 1,
      },
      {
        question: "What is 12 × 15?",
        options: ["150", "160", "170", "180"],
        correctAnswer: 3,
      },
      {
        question: "What is the area of a circle with a radius of 3 cm? (Use π = 3.14)",
        options: ["28.26 cm²", "31.42 cm²", "36.14 cm²", "39.14 cm²"],
        correctAnswer: 0,
      },
      {
        question: "What is the value of (8 + 2) × 3?",
        options: ["30", "32", "34", "28"],
        correctAnswer: 3,
      },
      {
        question: "What is the value of 50% of 80?",
        options: ["30", "35", "40", "45"],
        correctAnswer: 2,
      },
      {
        question: "What is the value of 25 ÷ 5 × 3?",
        options: ["12", "15", "18", "20"],
        correctAnswer: 1,
      },
    ],
  },

  {
    category: "entertainment",
    questions: [
      {
        question: "Who won the Academy Award for Best Actor in 2022?",
        options: ["Leonardo DiCaprio", "Will Smith", "Joaquin Phoenix", "Matthew McConaughey"],
        correctAnswer: 1,
      },
      {
        question: "Which movie won the Academy Award for Best Picture in 2021?",
        options: ["Parasite", "1917", "The Shape of Water", "Nomadland"],
        correctAnswer: 3,
      },
      {
        question: "Who played the character of Jack Dawson in the movie Titanic?",
        options: ["Leonardo DiCaprio", "Brad Pitt", "Johnny Depp", "Tom Hanks"],
        correctAnswer: 0,
      },
      {
        question: "Which TV show featured the characters Daenerys Targaryen and Jon Snow?",
        options: ["Breaking Bad", "Game of Thrones", "The Witcher", "Vikings"],
        correctAnswer: 1,
      },
      {
        question: "Who is known as the 'King of Pop'?",
        options: ["Michael Jackson", "Prince", "Whitney Houston", "Elvis Presley"],
        correctAnswer: 0,
      },
      {
        question: "Which superhero is known for saying, 'I am Iron Man'?",
        options: ["Black Panther", "Captain America", "Thor", "Iron Man"],
        correctAnswer: 3,
      },
      {
        question: "Which movie franchise includes a character named Luke Skywalker?",
        options: ["Guardians of the Galaxy", "Star Wars", "The Matrix", "Star Trek"],
        correctAnswer: 1,
      },
      {
        question: "Who played the character of Hermione Granger in the Harry Potter film series?",
        options: ["Emma Watson", "Anne Hathaway", "Maggie Smith", "Natalie Portman"],
        correctAnswer: 0,
      },
      {
        question: "Who directed the movie 'Inception'?",
        options: ["James Cameron", "Steven Spielberg", "Christopher Nolan", "Martin Scorsese"],
        correctAnswer: 2,
      },
      {
        question: "Which artist released the album 'Lover' in 2019?",
        options: ["Billie Eilish", "Taylor Swift", "Ed Sheeran", "Ariana Grande"],
        correctAnswer: 1,
      },
      {
        question: "What was the first video game to feature Mario?",
        options: ["Mario Kart", "Super Mario Bros.", "Donkey Kong", "The Legend of Zelda"],
        correctAnswer: 2,
      },
      {
        question: "Which movie features the famous line, 'Here's looking at you, kid'?",
        options: ["Casablanca", "Citizen Kane", "The Godfather", "Gone with the Wind"],
        correctAnswer: 0,
      },
      {
        question: "Which country won the FIFA World Cup in 2018?",
        options: ["France", "Germany", "Argentina", "Brazil"],
        correctAnswer: 0,
      },
      {
        question: "Who created the comic book character Spider-Man?",
        options: ["Jack Kirby", "Stan Lee", "Steve Ditko", "John Romita"],
        correctAnswer: 1,
      },
      {
        question: "In which movie did Heath Ledger portray the Joker?",
        options: ["The Dark Knight", "Batman Begins", "The Dark Knight Rises", "Joker"],
        correctAnswer: 0,
      },
      {
        question: "Which band is known for the hit song 'Bohemian Rhapsody'?",
        options: ["The Rolling Stones", "Led Zeppelin", "Queen", "The Beatles"],
        correctAnswer: 2,
      },
      {
        question: "Which actress starred as Katniss Everdeen in 'The Hunger Games'?",
        options: ["Kristen Stewart", "Shailene Woodley", "Jennifer Lawrence", "Emma Stone"],
        correctAnswer: 2,
      },
      {
        question: "Who played the role of the Joker in the 2019 movie 'Joker'?",
        options: ["Heath Ledger", "Johnny Depp", "Joaquin Phoenix", "Jared Leto"],
        correctAnswer: 2,
      },
      {
        question: "Which Disney animated film features the song 'A Whole New World'?",
        options: ["Cinderella", "Aladdin", "Beauty and the Beast", "The Little Mermaid"],
        correctAnswer: 1,
      },
      {
        question: "Which TV series features the characters of Walter White and Jesse Pinkman?",
        options: ["Narcos", "Better Call Saul", "The Sopranos", "Breaking Bad"],
        correctAnswer: 3,
      },
      {
        question: "Who sang the hit song 'Shape of You'?",
        options: ["Justin Bieber", "Ariana Grande", "Sam Smith", "Ed Sheeran"],
        correctAnswer: 3,
      },
      {
        question: "Which film won the Academy Award for Best Picture in 2020?",
        options: ["The Irishman", "Once Upon a Time in Hollywood", "Parasite", "1917"],
        correctAnswer: 2,
      },
      {
        question: "What year did the movie 'The Matrix' release?",
        options: ["1997", "1998", "2000", "1999"],
        correctAnswer: 3,
      },
      {
        question: "Which actor played Tony Stark/Iron Man in the Marvel Cinematic Universe?",
        options: ["Mark Ruffalo", "Chris Evans", "Robert Downey Jr.", "Chris Hemsworth"],
        correctAnswer: 2,
      },
      {
        question: "Which singer is known as the 'Queen of Pop'?",
        options: ["Mariah Carey", "Lady Gaga", "Whitney Houston", "Madonna"],
        correctAnswer: 3,
      },
    ],
  },
];

In your javascript/script.js file, add JavaScript to bring functionality to your quiz app. This includes initializing the quiz based on the user’s selections, handling the 15-second timer for each question, updating the score after each answer, and displaying the final results once the quiz is finished.

// DOM element selectors
const configContainer = document.querySelector(".config-container");
const quizContainer = document.querySelector(".quiz-container");
const answerOptions = quizContainer.querySelector(".answer-options");
const nextQuestionBtn = quizContainer.querySelector(".next-question-btn");
const questionStatus = quizContainer.querySelector(".question-status");
const timerDisplay = quizContainer.querySelector(".timer-duration");
const resultContainer = document.querySelector(".result-container");

// Quiz state variables
const QUIZ_TIME_LIMIT = 15;
let currentTime = QUIZ_TIME_LIMIT;
let timer = null;
let quizCategory = "programming";
let numberOfQuestions = 3;
let currentQuestion = null;
const questionsIndexHistory = [];
let correctAnswersCount = 0;
let disableSelection = false;

// Display the quiz result and hide the quiz container
const showQuizResult = () => {
  clearInterval(timer);
  resultContainer.style.display = "block";
  quizContainer.style.display = "none";

  const resultText = `You answered <b>${correctAnswersCount}</b> out of <b>${numberOfQuestions}</b> questions correctly. Great effort!`;
  resultContainer.querySelector(".result-message").innerHTML = resultText;
};

// Clear and reset the timer
const resetTimer = () => {
  clearInterval(timer);
  currentTime = QUIZ_TIME_LIMIT;
  timerDisplay.textContent = `${currentTime}s`;
};

// Initialize and start the timer for the current question
const startTimer = () => {
  timer = setInterval(() => {
    currentTime--;
    timerDisplay.textContent = `${currentTime}s`;

    if (currentTime <= 0) {
      clearInterval(timer);
      disableSelection = true;
      nextQuestionBtn.style.visibility = "visible";
      quizContainer.querySelector(".quiz-timer").style.background = "#c31402";
      highlightCorrectAnswer();

      // Disable all answer options after one option is selected
      answerOptions.querySelectorAll(".answer-option").forEach((option) => (option.style.pointerEvents = "none"));
    }
  }, 1000);
};

// Fetch a random question from based on the selected category
const getRandomQuestion = () => {
  const categoryQuestions = questions.find((cat) => cat.category.toLowerCase() === quizCategory.toLowerCase())?.questions || [];

  // Show the results if all questions have been used
  if (questionsIndexHistory.length >= Math.min(numberOfQuestions, categoryQuestions.length)) {
    return showQuizResult();
  }

  // Filter out already asked questions and choose a random one
  const availableQuestions = categoryQuestions.filter((_, index) => !questionsIndexHistory.includes(index));
  const randomQuestion = availableQuestions[Math.floor(Math.random() * availableQuestions.length)];

  questionsIndexHistory.push(categoryQuestions.indexOf(randomQuestion));
  return randomQuestion;
};

// Highlight the correct answer option and add icon
const highlightCorrectAnswer = () => {
  const correctOption = answerOptions.querySelectorAll(".answer-option")[currentQuestion.correctAnswer];
  correctOption.classList.add("correct");
  const iconHTML = `<span class="material-symbols-rounded"> check_circle </span>`;
  correctOption.insertAdjacentHTML("beforeend", iconHTML);
};

// Handle the user's answer selection
const handleAnswer = (option, answerIndex) => {
  if (disableSelection) return;
  clearInterval(timer);
  disableSelection = true;

  const isCorrect = currentQuestion.correctAnswer === answerIndex;
  option.classList.add(isCorrect ? "correct" : "incorrect");
  !isCorrect ? highlightCorrectAnswer() : correctAnswersCount++;

  // Insert icon based on correctness
  const iconHTML = `<span class="material-symbols-rounded"> ${isCorrect ? "check_circle" : "cancel"} </span>`;
  option.insertAdjacentHTML("beforeend", iconHTML);

  // Disable all answer options after one option is selected
  answerOptions.querySelectorAll(".answer-option").forEach((option) => (option.style.pointerEvents = "none"));

  nextQuestionBtn.style.visibility = "visible";
};

// Render the current question and its options in the quiz
const renderQuestion = () => {
  currentQuestion = getRandomQuestion();
  if (!currentQuestion) return;
  disableSelection = false;

  resetTimer();
  startTimer();

  // Update the UI
  nextQuestionBtn.style.visibility = "hidden";
  quizContainer.querySelector(".quiz-timer").style.background = "#32313C";
  quizContainer.querySelector(".question-text").textContent = currentQuestion.question;
  questionStatus.innerHTML = `<b>${questionsIndexHistory.length}</b> of <b>${numberOfQuestions}</b> Questions`;
  answerOptions.innerHTML = "";

  // Create option <li> elements, append them, and add click event listeners
  currentQuestion.options.forEach((option, index) => {
    const li = document.createElement("li");
    li.classList.add("answer-option");
    li.textContent = option;
    answerOptions.append(li);
    li.addEventListener("click", () => handleAnswer(li, index));
  });
};

// Start the quiz and render the random question
const startQuiz = () => {
  configContainer.style.display = "none";
  quizContainer.style.display = "block";

  // Update the quiz category and number of questions
  quizCategory = configContainer.querySelector(".category-option.active").textContent;
  numberOfQuestions = parseInt(configContainer.querySelector(".question-option.active").textContent);

  renderQuestion();
};

// Highlight the selected option on click - category or no. of question
configContainer.querySelectorAll(".category-option, .question-option").forEach((option) => {
  option.addEventListener("click", () => {
    option.parentNode.querySelector(".active").classList.remove("active");
    option.classList.add("active");
  });
});

// Reset the quiz and return to the configuration container
const resetQuiz = () => {
  resetTimer();
  correctAnswersCount = 0;
  questionsIndexHistory.length = 0;
  configContainer.style.display = "block";
  resultContainer.style.display = "none";
};

// Event listeners
nextQuestionBtn.addEventListener("click", renderQuestion);
resultContainer.querySelector(".try-again-btn").addEventListener("click", resetQuiz);
configContainer.querySelector(".start-quiz-btn").addEventListener("click", startQuiz);

That’s it! If you’ve added the code correctly, you’re ready to see and interact with your quiz app. Open the index.html file in your preferred browser to view the quiz project in action.

Conclusion and final words

And that’s it – you’ve built your very own quiz app with a timer using HTML, CSS, and JavaScript! This project is a fantastic way to boost your web development skills while creating something fun and interactive. Whether you’re making it for personal use, a client, or to showcase in your portfolio, it’s a great way to apply key web development concepts.

You can always take it further by adding more features like multiple quiz categories, different difficulty levels, or even a leaderboard to track high scores. The possibilities are endless, so don’t be afraid to get creative and expand your app!

If you enjoyed building this quiz app, you might also like my previous blog post on How to Build an AI Chatbot with HTML, CSS, and JavaScript. It’s another fun project that combines interactive web development with JavaScript to create a smart, engaging, and AI chatbot.

 

Previous articleBuild an AI Chatbot in React JS & CSS | Step-By-Step Guide

LEAVE A REPLY

Please enter your comment!
Please enter your name here