Loading lessons...
Project 3: Simple Quiz
Project 3: Simple Quiz
Build a quiz that checks answers and shows the score.
Step 1: The HTML
<h2>What is 2 + 2?</h2>
<button data-answer="3">3</button>
<button data-answer="4">4</button>
<button data-answer="5">5</button>
<p id="result"></p>
<p id="score">Score: 0</p>
Step 2: The JavaScript
let score = 0;
const result = document.getElementById("result");
const scoreEl = document.getElementById("score");
document.querySelectorAll("button").forEach(function(btn) {
btn.addEventListener("click", function() {
if (btn.dataset.answer === "4") {
result.textContent = "Correct!";
score++;
} else {
result.textContent = "Wrong, try again.";
}
scoreEl.textContent = "Score: " + score;
});
});
Step 3: How it works
querySelectorAllgrabs every answer button.forEachattaches a listener to each one.btn.dataset.answerreads the data-answer attribute.- Correct answers increase the score.
Bonus ideas
- Add multiple questions.
- Show a final message when the quiz ends.
- Shuffle the answers.
TL;DR
- querySelectorAll returns a list of matching elements.
- dataset reads data-* attributes.
- forEach attaches behavior to each element.
- Track state in a variable like score.