🧠 Build a Simple JavaScript Quiz App
A basic interactive quiz using JavaScript. Practice DOM manipulation, conditionals, and event handling.
📄 HTML Markup
<div id="quiz-container">
<h2 id="question"></h2>
<ul id="answers"></ul>
<button id="nextBtn">Next</button>
</div>
📜 JavaScript Logic
const questions = [
{
question: "Which language runs in a web browser?",
options: ["Java", "C", "Python", "JavaScript"],
answer: "JavaScript"
},
{
question: "What does CSS stand for?",
options: ["Central Style Sheets", "Cascading Style Sheets", "Colorful Style Sheets", "Computer Style Sheets"],
answer: "Cascading Style Sheets"
},
{
question: "What is HTML?",
options: ["Programming Language", "Markup Language", "Database", "Framework"],
answer: "Markup Language"
}
];
let currentQuestion = 0;
let score = 0;
const questionEl = document.getElementById("question");
const answersEl = document.getElementById("answers");
const nextBtn = document.getElementById("nextBtn");
function loadQuestion() {
const q = questions[currentQuestion];
questionEl.textContent = q.question;
answersEl.innerHTML = "";
q.options.forEach(option => {
const li = document.createElement("li");
li.textContent = option;
li.classList.add("cursor-pointer", "hover:text-blue-500", "mb-2");
li.addEventListener("click", () => {
if (option === q.answer) {
li.classList.add("text-green-600");
score++;
} else {
li.classList.add("text-red-600");
}
[...answersEl.children].forEach(btn => btn.style.pointerEvents = "none");
});
answersEl.appendChild(li);
});
}
nextBtn.addEventListener("click", () => {
currentQuestion++;
if (currentQuestion < questions.length) {
loadQuestion();
} else {
questionEl.textContent = \`🎉 Quiz Finished! Your score: \${score}/\${questions.length}\`;
answersEl.innerHTML = "";
nextBtn.style.display = "none";
}
});
loadQuestion();
🎨 Optional Styling
<style>
#quiz-container {
max-width: 500px;
margin: auto;
text-align: left;
}
#answers li {
list-style: none;
padding: 10px;
border: 1px solid #ddd;
margin-bottom: 8px;
border-radius: 5px;
}
#nextBtn {
padding: 10px 20px;
background-color: #2563eb;
color: white;
border: none;
border-radius: 4px;
}
</style>
✅ Tip: Add a timer, randomize questions, or save high scores with
localStorage
.
📚 What You Practice
- DOM manipulation
- Event handling
- Conditional logic
- Dynamic UI generation