SmartCodingTips

🧠 Advanced JavaScript Quiz App

Build an interactive multiple-choice quiz app with JavaScript that includes question navigation, score tracking, dynamic feedback, and a final result screen.

📄 HTML Layout

<div id="quiz-container">
  <h2 id="question"></h2>
  <div id="answers"></div>
  <button id="next-btn">Next</button>
  <p id="score" class="mt-4 font-semibold"></p>
</div>

🧠 JavaScript Logic

const questions = [
  {
    question: "Which method is used to parse JSON in JavaScript?",
    options: ["JSON.parse()", "JSON.stringify()", "parseJSON()", "convertJSON()"],
    answer: "JSON.parse()"
  },
  {
    question: "What does '===' mean?",
    options: ["Assignment", "Strict equality", "Loose equality", "Compare by value"],
    answer: "Strict equality"
  },
  // Add more questions as needed
];

let currentIndex = 0;
let score = 0;

const questionEl = document.getElementById("question");
const answersEl = document.getElementById("answers");
const nextBtn = document.getElementById("next-btn");
const scoreEl = document.getElementById("score");

function showQuestion() {
  const q = questions[currentIndex];
  questionEl.textContent = q.question;
  answersEl.innerHTML = "";

  q.options.forEach(option => {
    const btn = document.createElement("button");
    btn.textContent = option;
    btn.classList.add("bg-blue-100", "hover:bg-blue-200", "m-1", "p-2", "rounded");
    btn.onclick = () => selectAnswer(btn, q.answer);
    answersEl.appendChild(btn);
  });
}

function selectAnswer(selectedBtn, correctAnswer) {
  const isCorrect = selectedBtn.textContent === correctAnswer;
  if (isCorrect) {
    selectedBtn.classList.add("bg-green-300");
    score++;
  } else {
    selectedBtn.classList.add("bg-red-300");
  }

  Array.from(answersEl.children).forEach(btn => {
    btn.disabled = true;
    if (btn.textContent === correctAnswer) {
      btn.classList.add("border", "border-green-600");
    }
  });

  nextBtn.style.display = "block";
}

nextBtn.onclick = () => {
  currentIndex++;
  if (currentIndex < questions.length) {
    showQuestion();
    nextBtn.style.display = "none";
  } else {
    showResult();
  }
};

function showResult() {
  questionEl.textContent = "🎉 Quiz Complete!";
  answersEl.innerHTML = "";
  nextBtn.style.display = "none";
  scoreEl.textContent = `You scored ${score} out of ${questions.length}`;
}

showQuestion();

✨ Features You Can Add

  • Timer per question
  • Progress bar
  • Randomized questions
  • LocalStorage for high scores
  • Category-based quiz filtering
💡 Tip: Wrap questions in a JSON file for loading via fetch() to make it scalable.