Create an interactive quiz with HTML, CSS, andJavaScript with question list in question.json

Hey, I am Ajink, and today in this blog, we’re going to create an engaging and interactive quiz using HTML, CSS, and JavaScript. The questions for the quiz are stored in a questions.json file, allowing for easy management and modification.

HTML Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Interactive Quiz</title>
</head>
<body>
  <div class="quiz-container">
    <h1>Interactive Quiz</h1>
    <div id="question-container" class="question-container"></div>
    <button id="next-btn" onclick="nextQuestion()">Next</button>
    <p id="result"></p>
  </div>
  <script src="app.js"></script>
</body>
</html>

HTML Code Explanation:

  • The HTML structure consists of a container for the quiz, a div to display the questions dynamically, a “Next” button, and a paragraph to show the quiz result.

CSS Code:

body {
  margin: 0;
  font-family: 'Arial', sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #f0f0f0;
}

.quiz-container {
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 20px;
  text-align: center;
}

.question-container {
  margin: 20px 0;
}

button {
  background-color: #3498db;
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

#result {
  font-weight: bold;
}

CSS Code Explanation:

  • The CSS provides styling for the quiz container, question display, and the “Next” button.

JavaScript Code:

let currentQuestionIndex = 0;
let score = 0;

document.addEventListener('DOMContentLoaded', function () {
  loadQuestion(currentQuestionIndex);
});

function loadQuestion(index) {
  const questionContainer = document.getElementById('question-container');
  const nextBtn = document.getElementById('next-btn');
  const resultElement = document.getElementById('result');

  fetch('questions.json')
    .then(response => response.json())
    .then(data => {
      const questions = data.questions;

      if (index >= 0 && index < questions.length) {
        const currentQuestion = questions[index];

        questionContainer.innerHTML = `
          <h2>${currentQuestion.question}</h2>
          <ul>
            ${currentQuestion.options.map(option => `<li onclick="checkAnswer('${option}')">${option}</li>`).join('')}
          </ul>
        `;

        resultElement.innerText = '';
        nextBtn.style.display = 'none';
      } else {
        showResult();
      }
    })
    .catch(error => console.error('Error loading questions:', error));
}

function checkAnswer(selectedOption) {
  const questionContainer = document.getElementById('question-container');
  const nextBtn = document.getElementById('next-btn');
  const resultElement = document.getElementById('result');

  fetch('questions.json')
    .then(response => response.json())
    .then(data => {
      const currentQuestion = data.questions[currentQuestionIndex];

      if (currentQuestion.correctAnswer === selectedOption) {
        score++;
      }

      questionContainer.innerHTML = `<p>You selected: ${selectedOption}</p>`;
      resultElement.innerText = `Score: ${score}`;

      nextBtn.style.display = 'block';
    })
    .catch(error => console.error('Error checking answer:', error));
}

function nextQuestion() {
  currentQuestionIndex++;
  loadQuestion(currentQuestionIndex);
}

function showResult() {
  const questionContainer = document.getElementById('question-container');
  const nextBtn = document.getElementById('next-btn');
  const resultElement = document.getElementById('result');

  questionContainer.innerHTML = '';
  nextBtn.style.display = 'none';
  resultElement.innerText = `Quiz completed! Your final score is ${score}.`;
}

JavaScript Code Explanation:

  • The JavaScript code loads questions from the questions.json file.
  • The loadQuestion function dynamically generates HTML for the current question and options.
  • The checkAnswer function checks the selected answer and updates the score.
  • The nextQuestion function moves to the next question.
  • The showResult function displays the final quiz result.

questions.json:

{
  "questions": [
    {
      "question": "What is the capital of France?",
      "options": ["Berlin", "Paris", "Madrid", "Rome"],
      "correctAnswer": "Paris"
    },
    {
      "question": "Which planet is known as the Red Planet?",
      "options": ["Venus", "Mars", "Jupiter", "Saturn"],
      "correctAnswer": "Mars"
    },
    {
      "question": "What is the largest mammal in the world?",
      "options": ["Elephant", "Blue Whale", "Giraffe", "Hippopotamus"],
      "correctAnswer": "Blue Whale"
    }
  ]
}

Conclusion:

In this blog, we successfully created an interactive quiz using HTML, CSS, and JavaScript. The questions are stored in a questions.json file, making it easy to update and modify the quiz content. Don’t forget to subscribe to my YouTube channel at youtube.com/@ajink21 for more exciting tutorials.

Thanks for reading, and if you have any doubts, feel free to comment!

Ajink Gupta
Ajink Gupta
Articles: 54