Interactive JavaScript Quiz Game: Test Your Knowledge

17 Dec 2021 Balmiki Mandal 0 JavaScript

Create a Quiz Game in JavaScript

JavaScript is a powerful language that can be used to create a variety of interactive web applications, including quiz games. In this tutorial, we will show you how to create a simple quiz game with multiple-choice questions and feedback on correct/incorrect answers.

HTML

First, we need to create a basic HTML structure for our quiz game. This will include a container element for the quiz questions, a container element for the quiz results, and a submit button.

HTML

<div id="quiz"></div>
<div id="results"></div>
<button type="submit">Submit</button>

CSS

We can use CSS to style the quiz game however we like. For example, we can center the quiz questions and results, and add some padding and margins.

CSS
#quiz {
  width: 500px;
  margin: 0 auto;
}

#results {
  width: 500px;
  margin: 0 auto;
}

JavaScript

Now, we need to write the JavaScript code to power our quiz game. This code will be responsible for displaying the quiz questions, tracking the score, and providing feedback on correct/incorrect answers.

JavaScript
// Create an array of quiz questions
const questions = [
  {
    question: "What is the capital of France?",
    answers: ["Paris", "London", "Rome", "Berlin"],
    correctAnswer: "Paris",
  },
  {
    question: "What is the largest ocean in the world?",
    answers: ["Pacific Ocean", "Atlantic Ocean", "Indian Ocean", "Arctic Ocean"],
    correctAnswer: "Pacific Ocean",
  },
  {
    question: "What is the square root of 16?",
    answers: ["2", "4", "8", "16"],
    correctAnswer: "4",
  },
];

// Create a variable to track the current question index
let currentQuestionIndex = 0;

// Display the current quiz question
function displayQuestion() {
  const question = questions[currentQuestionIndex];
  const quizContainer = document.getElementById("quiz");

  quizContainer.innerHTML = `
    <h2>${question.question}</h2>
    <ul>
      ${question.answers.map((answer) => `<li><input type="radio" name="answer" value="${answer}">${answer}</li>`).join("")}
    </ul>
  `;
}

// Check the user's answer and provide feedback
function checkAnswer() {
  const quizContainer = document.getElementById("quiz");
  const selectedAnswer = quizContainer.querySelector('input[name="answer"]:checked');

  if (selectedAnswer) {
    const correctAnswer = questions[currentQuestionIndex].correctAnswer;

    if (selectedAnswer.value === correctAnswer) {
      alert("Correct!");
    } else {
      alert("Incorrect. The correct answer is " + correctAnswer);
    }

    // Move to the next question
    currentQuestionIndex++;

    if (currentQuestionIndex < questions.length) {
      displayQuestion();
    } else {
      // The quiz is over
      showResults();
    }
  } else {
    alert("Please select an answer.");
  }
}

// Display the quiz results
function showResults() {
  const resultsContainer = document.getElementById("results");

  let score = 0;
  for (let i = 0; i < questions.length; i++) {
    const question = questions[i];
    const correctAnswer = question.correctAnswer;

    if (localStorage.getItem(`question-${i}`) === correctAnswer) {
      score++;
    }
  }

  resultsContainer.innerHTML = `
    <h2>Quiz Results</h2>
    <p>You scored ${score} out of ${questions.length} questions correctly.</p>
  `;
}

// Add an event listener to the submit button to check the user's answer
document.querySelector("button[type='submit']").addEventListener("click", checkAnswer);

// Display the first quiz question
displayQuestion();

Conclusion

This is just a basic example of how to create a quiz game in JavaScript. You can customize it to add more features, such as a timer, different types of questions, and more

Top Resources Now:


Enroll Now:


[JavaScript 2023-2024: From Scratch to Advanced] "Start Supercharging Your Productivity!"

Contact Us:


  • For any inquiries, please email us at [[email protected]].
  • Follow us on insta  [ electro4u_offical_ ] for updates and tips.

 

Note: If you encounter any issues or specific errors when running this program, please let me know and I'll be happy to help debug them!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.