Time to put the lessons together. In this project you will build a working quiz app in a single HTML file: it shows one question at a time, marks the answer, keeps score, tracks progress and offers a restart. It uses arrays of objects, functions, template literals, DOM updates and events, which are the core skills from the earlier lessons. Play it below first, then read how it works.
In this project you will practise
- Storing data as an array of objects
- Keeping the app’s state in variables
- Rendering the page from that state
- Handling clicks with
addEventListener - Updating classes and styles to give feedback
Try the Finished App
Result
The Complete Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Quiz app</title>
<style>
body { font-family: sans-serif; max-width: 520px; margin: 0 auto; padding: 8px; }
.options button { display: block; width: 100%; margin: 6px 0; padding: 8px; text-align: left;
border: 1px solid #b0bec5; border-radius: 6px; background: #fff; cursor: pointer; }
.options button:disabled { cursor: default; }
.correct { background: #c8e6c9 !important; border-color: #2e7d32 !important; }
.wrong { background: #ffcdd2 !important; border-color: #c62828 !important; }
.bar { height: 6px; background: #eceff1; border-radius: 3px; }
.bar div { height: 100%; background: #00695c; border-radius: 3px; transition: width .3s; }
#next { margin-top: 8px; padding: 6px 16px; }
</style>
</head>
<body>
<div class="bar"><div id="progress"></div></div>
<p id="counter"></p>
<h3 id="question"></h3>
<div class="options" id="options"></div>
<p id="feedback"></p>
<button id="next" hidden>Next</button>
<script>
const questions = [
{ text: "Which keyword declares a variable that cannot be reassigned?",
options: ["var", "let", "const"], answer: 2 },
{ text: "What does [1, 2, 3].map(n => n * 2) return?",
options: ["[2, 4, 6]", "12", "[1, 2, 3]"], answer: 0 },
{ text: "Which method stops a form from reloading the page?",
options: ["stopPropagation()", "preventDefault()", "return false"], answer: 1 },
{ text: "What is typeof null?",
options: ["\"null\"", "\"undefined\"", "\"object\""], answer: 2 },
];
let current = 0;
let score = 0;
const el = (id) => document.getElementById(id);
function showQuestion() {
const q = questions[current];
el("counter").textContent = `Question ${current + 1} of ${questions.length}`;
el("progress").style.width = `${(current / questions.length) * 100}%`;
el("question").textContent = q.text;
el("feedback").textContent = "";
el("next").hidden = true;
el("options").innerHTML = "";
q.options.forEach((option, index) => {
const btn = document.createElement("button");
btn.textContent = option;
btn.addEventListener("click", () => checkAnswer(index));
el("options").append(btn);
});
}
function checkAnswer(chosen) {
const q = questions[current];
const buttons = el("options").querySelectorAll("button");
buttons.forEach((b) => (b.disabled = true));
buttons[q.answer].classList.add("correct");
if (chosen === q.answer) {
score++;
el("feedback").textContent = "Correct!";
} else {
buttons[chosen].classList.add("wrong");
el("feedback").textContent = "Not quite. The right answer is highlighted.";
}
el("next").textContent = current === questions.length - 1 ? "See result" : "Next";
el("next").hidden = false;
}
function showResult() {
el("progress").style.width = "100%";
el("counter").textContent = "Finished";
el("question").textContent = `You scored ${score} out of ${questions.length}`;
el("options").innerHTML = "";
el("feedback").textContent = score === questions.length ? "Perfect score!" : "Review the lessons and try again.";
el("next").textContent = "Restart";
}
el("next").addEventListener("click", () => {
if (el("next").textContent === "Restart") {
current = 0;
score = 0;
showQuestion();
} else if (current < questions.length - 1) {
current++;
showQuestion();
} else {
showResult();
}
});
showQuestion();
</script>
</body>
</html>
How It Works
1. The data
Each question is an object with its text, an array of options and the index of the correct answer. Adding a question means adding one object; no other code changes. This separation of data from logic is the most important idea in the project.
2. The state
Two variables, current (which question is showing) and score, describe everything about the quiz at any moment. The page is never the “source of truth”; it only displays these values.
3. Rendering
showQuestion() reads the current question and rebuilds the screen: the counter text, the progress bar width, the question and a fresh button for each option. Clearing innerHTML first removes the old buttons and their listeners. The option text is set with textContent, which is safe even if a question contains characters like <.
4. Checking answers
checkAnswer(chosen) disables all buttons so the user cannot answer twice, always highlights the correct option, adds the wrong class to a wrong choice and updates the score. The Next button appears only after an answer.
5. Moving on and restarting
The single Next button changes its job by its label: go to the next question, show the result after the last one, or reset current and score to restart. Because the screen is always drawn from state, restarting is just two assignments and a call to showQuestion().
Ideas to Extend the Project
| Feature | Skills it practises |
|---|---|
| Shuffle the questions each time | Arrays and Math.random |
| Add a 15-second timer per question | setInterval and clearInterval |
| Save the best score | localStorage |
| Load questions from a JSON file | fetch and async/await |
| Allow keyboard answers with keys 1 to 3 | keydown events |
| Turn the quiz into a class | classes and methods |
Common Mistakes When Building It
- Reading the score from the page instead of a variable, which breaks easily when the text changes.
- Adding listeners without removing old buttons, so one click counts several times.
- Not disabling buttons after an answer, letting users click until they find the right one.
- Off-by-one errors with
currentandquestions.lengthat the last question.
Practice Exercises
Exercise 1. Shuffle the questions before the quiz starts.
Show answer
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
shuffle(questions);
This is the Fisher–Yates shuffle. It gives every order an equal chance, unlike the popular sort(() => Math.random() - 0.5) trick.
Exercise 2. Show the percentage score on the result screen.
Show answer
const percent = Math.round((score / questions.length) * 100);
el("question").textContent = `You scored ${score} out of ${questions.length} (${percent}%)`;
Frequently Asked Questions
How do I run this project on my computer?
Copy the complete code into a file called quiz.html and open it in your browser. Everything is in one file, so no server or installation is needed.
What should I build next?
Good next projects are a to-do list with localStorage, a weather app using fetch and a public API, and a calculator. Each one adds one new skill to what you used here.
Summary
- Keep data (questions) separate from logic (functions).
- Store the app’s state in variables and draw the page from it.
- Rebuild elements with
createElementand attach listeners as you create them. - Give clear feedback with classes, disabled buttons and messages.
Next: JavaScript Map and Set.
