Tutorials JavaScript Project: Quiz App
Ch 74 / 78
Chapter 74 Advanced 25 min read JavaScript

Project: Build a Quiz App with JavaScript

Put everything you've learned together — arrays, DOM, events, timers, and state management — to build a polished, fully interactive Quiz App from scratch. No libraries. Pure JavaScript.

What you'll learn
Structure a quiz app with an array of question objects
Dynamically render questions and answer choices to the DOM
Track score and current question index with JS state
Add a per-question countdown timer with setInterval
Show a results screen with score and a restart button
Shuffle questions and randomise answer order

Project Overview

We'll build a multi-question Quiz App entirely with HTML, CSS, and vanilla JavaScript. Users pick an answer, get instant feedback (correct / wrong highlighted), then the next question loads automatically. At the end they see a score summary and can restart.

Question Bank
An array of objects — each with a question string, four choices, and the correct answer index.
Countdown Timer
15 seconds per question. If time runs out, the correct answer is revealed and the app moves on.
Score Tracking
A live score counter updates after every correct answer. Final score displayed as a percentage.
Restart Support
One-click restart resets state and shuffles questions so every attempt feels fresh.

Project File Structure

Keep the project simple — three files is all you need:

quiz-app/
index.html  — markup & layout
style.css   — all visual styling
app.js     — quiz logic & DOM control
Pro Tip
Keep all logic in app.js. Avoid inline onclick attributes — attach event listeners programmatically so your HTML stays clean and your code is testable.

App Flow

Before writing a single line, map out the lifecycle of the app:

INIT
Shuffle questions and reset score + index to 0. Render the first question.
SHOW Q
Display the current question, render answer buttons, and start the 15 s timer.
ANSWER
User clicks a choice — stop the timer, highlight correct (green) and wrong (red), increment score if correct.
NEXT
After a 1 s delay, advance the index. If more questions remain, go to SHOW Q. Otherwise, go to RESULTS.
RESULTS
Show final score as X / N and percentage. Display a "Play Again" button that restarts at INIT.

Step 1 — HTML Structure

index.html

The HTML is deliberately minimal — JavaScript will fill in all the dynamic content. We only need skeleton containers:

HTML — index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>JS Quiz App</title>
  <link rel="stylesheet" href="style.css" />
</head>
<body>

  <div class="quiz-wrapper">

    <!-- ── Start Screen ──────────────────── -->
    <div class="screen" id="start-screen">
      <h1>⚡ JS Quiz</h1>
      <p>10 questions · 15 s each · Multiple choice</p>
      <button id="start-btn">Start Quiz</button>
    </div>

    <!-- ── Quiz Screen ───────────────────── -->
    <div class="screen hidden" id="quiz-screen">
      <div class="quiz-header">
        <span id="question-num"></span>
        <span class="timer" id="timer">15</span>
        <span id="score-display">Score: 0</span>
      </div>
      <div class="progress-bar">
        <div class="progress-fill" id="progress-fill"></div>
      </div>
      <p class="question-text" id="question-text"></p>
      <div class="options" id="options"></div>
    </div>

    <!-- ── Results Screen ────────────────── -->
    <div class="screen hidden" id="result-screen">
      <h2>Quiz Complete! 🎉</h2>
      <div class="result-score" id="result-score"></div>
      <div class="result-msg"  id="result-msg"></div>
      <button id="restart-btn">🔁 Play Again</button>
    </div>

  </div>

  <script src="app.js"></script>
</body>
</html>
#start-screen
Shown on page load. Hides when the user clicks "Start Quiz".
#quiz-screen
Active during the quiz. JS populates #question-text and #options dynamically each round.
#result-screen
Shown after all questions are answered. Displays final score and a restart button.
.hidden
A CSS utility class (display: none) toggled via JS to switch between screens.

Step 2 — CSS Styling

style.css

The styles give the app a dark, modern card look. Pay attention to the .correct and .wrong answer states — these are toggled by JS to provide instant feedback.

CSS — style.css
/* ── Reset & Base ─────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

body {
  font-family: 'Segoe UI', sans-serif;
  background: #0d0d16;
  color: #f0f0e8;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

/* ── Wrapper card ──────────────────────────────────── */
.quiz-wrapper {
  background: #161622;
  border: 1px solid rgba(255,255,255,.08);
  border-radius: 20px;
  padding: 40px 36px;
  width: 100%;
  max-width: 560px;
  box-shadow: 0 24px 60px rgba(0,0,0,.5);
}

/* ── Screen toggle ─────────────────────────────────── */
.screen        { display: block; }
.screen.hidden { display: none; }

/* ── Start Screen ──────────────────────────────────── */
#start-screen { text-align: center; }
#start-screen h1 { font-size: 2.4rem; margin-bottom: 10px; }
#start-screen p  { color: #a8a89c; margin-bottom: 28px; }

/* ── Buttons ────────────────────────────────────────── */
button {
  background: #f7df1e;
  color: #1a1a14;
  border: none;
  padding: 13px 32px;
  border-radius: 10px;
  font-size: 15px;
  font-weight: 700;
  cursor: pointer;
  transition: transform .15s, filter .15s;
}
button:hover { transform: scale(1.04); filter: brightness(1.08); }

/* ── Quiz header bar ────────────────────────────────── */
.quiz-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 13px;
  color: #a8a89c;
}

.timer {
  font-size: 22px;
  font-weight: 700;
  color: #f7df1e;
  min-width: 32px;
  text-align: center;
  transition: color .3s;
}
.timer.urgent { color: #ef4444; }

/* ── Progress bar ───────────────────────────────────── */
.progress-bar {
  height: 5px;
  background: rgba(255,255,255,.07);
  border-radius: 99px;
  margin-bottom: 24px;
  overflow: hidden;
}
.progress-fill {
  height: 100%;
  background: #f7df1e;
  border-radius: 99px;
  transition: width .4s;
}

/* ── Question text ──────────────────────────────────── */
.question-text {
  font-size: 1.15rem;
  font-weight: 600;
  line-height: 1.55;
  margin-bottom: 22px;
  color: #f0f0e8;
}

/* ── Answer options ─────────────────────────────────── */
.options { display: flex; flex-direction: column; gap: 10px; }

.option-btn {
  background: rgba(255,255,255,.04);
  border: 1px solid rgba(255,255,255,.1);
  color: #f0f0e8;
  text-align: left;
  padding: 13px 18px;
  border-radius: 10px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background .2s, border-color .2s;
}
.option-btn:hover:not(.disabled) {
  background: rgba(247,223,30,.08);
  border-color: rgba(247,223,30,.4);
}
.option-btn.correct {
  background: rgba(34,197,94,.15);
  border-color: #22c55e;
  color: #22c55e;
}
.option-btn.wrong {
  background: rgba(239,68,68,.15);
  border-color: #ef4444;
  color: #ef4444;
}
.option-btn.disabled { cursor: not-allowed; opacity: .7; }

/* ── Results screen ─────────────────────────────────── */
#result-screen { text-align: center; }
#result-screen h2 { font-size: 1.8rem; margin-bottom: 16px; }
.result-score { font-size: 3rem; font-weight: 800; color: #f7df1e; margin-bottom: 8px; }
.result-msg   { color: #a8a89c; margin-bottom: 28px; font-size: 15px; }
Note
The .correct, .wrong, and .disabled classes are the key to instant visual feedback — they are added entirely by JavaScript and never hard-coded in HTML.
⚡
Free Resource
Download our JavaScript Cheat Sheet
Syntax, built-in methods, ES6+ features — all on one page.
Get Sheet

Step 3 — JavaScript Logic

app.js

This is the heart of the project. We'll break it into logical blocks:

A — Question Bank

JS — questions array
// Each object: question string, array of 4 choices, correct answer index (0-based)
const questions = [
  {
    q: "Which keyword declares a block-scoped variable in JS?",
    choices: ["var", "let", "define", "set"],
    answer: 1
  },
  {
    q: "What does DOM stand for?",
    choices: ["Document Object Model", "Data Object Map", "Dynamic Output Mode", "Document Order Manager"],
    answer: 0
  },
  {
    q: "Which method adds an item to the END of an array?",
    choices: ["unshift()", "shift()", "push()", "pop()"],
    answer: 2
  },
  {
    q: "What is the output of: typeof null?",
    choices: ["'null'", "'undefined'", "'object'", "'boolean'"],
    answer: 2
  },
  {
    q: "Which ES6 feature lets you embed expressions inside strings?",
    choices: ["String.format()", "Template Literals", "concat()", "Interpolation tags"],
    answer: 1
  },
  {
    q: "Which function runs code after a specified delay (once)?",
    choices: ["setInterval()", "delay()", "setTimeout()", "runLater()"],
    answer: 2
  },
  {
    q: "What does === check in JavaScript?",
    choices: ["Value only", "Type only", "Value and type", "Reference equality"],
    answer: 2
  },
  {
    q: "Which array method returns a new array of filtered items?",
    choices: ["map()", "reduce()", "find()", "filter()"],
    answer: 3
  },
  {
    q: "Which keyword is used to handle a Promise rejection?",
    choices: ["catch", "reject", "error", "fail"],
    answer: 0
  },
  {
    q: "Arrow functions do NOT have their own ___.",
    choices: ["return value", "parameters", "this keyword", "name"],
    answer: 2
  }
];

B — State Variables & Timer

JS — state & timer
// ── State ───────────────────────────────────────────────
let currentIndex = 0;   // which question we're on
let score        = 0;   // correct answers so far
let timerID      = null; // holds the setInterval reference
let shuffled      = [];  // questions after shuffle

// ── DOM refs ─────────────────────────────────────────────
const startScreen  = document.getElementById("start-screen");
const quizScreen   = document.getElementById("quiz-screen");
const resultScreen = document.getElementById("result-screen");
const qNumEl       = document.getElementById("question-num");
const qTextEl      = document.getElementById("question-text");
const optionsEl    = document.getElementById("options");
const timerEl      = document.getElementById("timer");
const progressEl   = document.getElementById("progress-fill");
const scoreEl      = document.getElementById("score-display");
const resultScoreEl = document.getElementById("result-score");
const resultMsgEl  = document.getElementById("result-msg");

// ── Timer ────────────────────────────────────────────────
function startTimer() {
  let timeLeft = 15;
  timerEl.textContent = timeLeft;
  timerEl.classList.remove("urgent");

  timerID = setInterval(() => {
    timeLeft--;
    timerEl.textContent = timeLeft;
    if (timeLeft <= 5) timerEl.classList.add("urgent");
    if (timeLeft <= 0) {
      clearInterval(timerID);
      revealAnswer(-1); // -1 means "time's up, no choice made"
      setTimeout(loadNextQuestion, 1200);
    }
  }, 1000);
}

function stopTimer() {
  clearInterval(timerID);
}

C — Render Question & Handle Answer

JS — render & answer
function showQuestion() {
  const q = shuffled[currentIndex];

  // Header info
  qNumEl.textContent = `Q ${currentIndex + 1} / ${shuffled.length}`;
  scoreEl.textContent = `Score: ${score}`;

  // Progress bar
  progressEl.style.width = `${(currentIndex / shuffled.length) * 100}%`;

  // Question text
  qTextEl.textContent = q.q;

  // Answer buttons
  optionsEl.innerHTML = "";
  q.choices.forEach((choice, idx) => {
    const btn = document.createElement("button");
    btn.className = "option-btn";
    btn.textContent = choice;
    btn.addEventListener("click", () => handleAnswer(idx));
    optionsEl.appendChild(btn);
  });

  startTimer();
}

function handleAnswer(selectedIdx) {
  stopTimer();
  revealAnswer(selectedIdx);

  if (selectedIdx === shuffled[currentIndex].answer) {
    score++;
    scoreEl.textContent = `Score: ${score}`;
  }

  setTimeout(loadNextQuestion, 1200);
}

function revealAnswer(selectedIdx) {
  const correctIdx = shuffled[currentIndex].answer;
  const btns = optionsEl.querySelectorAll(".option-btn");

  btns.forEach((btn, idx) => {
    btn.classList.add("disabled");
    if (idx === correctIdx) btn.classList.add("correct");
    else if (idx === selectedIdx) btn.classList.add("wrong");
  });
}

D — Flow Control & Initialisation

JS — flow control
function loadNextQuestion() {
  currentIndex++;
  if (currentIndex < shuffled.length) {
    showQuestion();
  } else {
    showResults();
  }
}

function showResults() {
  quizScreen.classList.add("hidden");
  resultScreen.classList.remove("hidden");
  progressEl.style.width = "100%";

  const pct = Math.round((score / shuffled.length) * 100);
  resultScoreEl.textContent = `${score} / ${shuffled.length}`;

  const msgs = [
    [80, "🏆 Excellent! You're a JavaScript pro!"],
    [60, "👍 Good job! Keep practising!"],
    [0,  "📖 Keep studying — you'll get there!"]
  ];
  resultMsgEl.textContent = msgs.find(([min]) => pct >= min)[1];
}

// Fisher-Yates shuffle
function shuffle(arr) {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

function startQuiz() {
  currentIndex = 0;
  score = 0;
  shuffled = shuffle(questions);
  startScreen.classList.add("hidden");
  resultScreen.classList.add("hidden");
  quizScreen.classList.remove("hidden");
  showQuestion();
}

// Event listeners
document.getElementById("start-btn").addEventListener("click", startQuiz);
document.getElementById("restart-btn").addEventListener("click", startQuiz);

JavaScript Concepts Used

This project deliberately exercises many core JS skills at once:

Concept Where it appears Chapter ref
Arrays & Objects The questions array Ch 30, 35
DOM Manipulation Creating/appending option buttons; toggling screens Ch 40–42
Event Listeners click on each answer button, Start & Restart Ch 43
setInterval / clearInterval The countdown timer per question Ch 46
Closures / State currentIndex, score, timerID Ch 26
Arrow Functions Timer callback, forEach, find Ch 25
Template Literals Score display, progress percentage Ch 9
Array Destructuring / Spread Fisher-Yates shuffle, result message lookup Ch 33, 34

Challenge: Extend the App

Once the core app works, try these upgrades to level up:

Difficulty Filter
Add an easy | medium | hard property to each question object. Show a difficulty selector on the Start screen and .filter() questions before shuffling.
High Score (localStorage)
Save the best score with localStorage.setItem() and display it on the results screen. Persist across page refreshes.
Answer Review
After the quiz ends, show a list of every question with the user's choice and the correct answer highlighted — great UX for learning.
Fetch Questions from API
Use the Open Trivia DB API (opentdb.com) to load questions dynamically instead of hard-coding them. Great practice for Fetch + async/await.
Advertisement

Try It Yourself

Live Editor — Full Quiz App
✎ Editor
👁 Preview
Quick Check — Chapter 74

Which JavaScript function repeatedly executes a callback after a fixed interval?

Chapter Summary
  • A Quiz App is a great project to combine arrays, DOM manipulation, events, timers, and state management in one place.
  • Store questions in an array of objects with a question, choices array, and answer index.
  • Use setInterval for the countdown timer and always call clearInterval when the user answers or time expires.
  • Toggle CSS classes (.correct, .wrong, .disabled) to provide instant visual feedback without touching innerHTML directly.
  • Use a Fisher-Yates shuffle to randomise question order on every restart.
  • Extend the app with localStorage for high scores, difficulty filters, or a live API for fresh questions every time.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel