Build a Quiz Game Using HTML CSS and JavaScript

Build a Quiz Game Using HTML CSS & JavaScript

Introduction

Hello friends, welcome to today’s new blog. Today’s project is going to be very amazing because today we have created an interesting project for you which is a quiz game. We have created this quiz game with the help of html css and javascript which is quite an easy task. If you have knowledge of javascript then you can easily make this quiz game, but friends, if you do not have knowledge of coding and you want to develop a game like this, then you have come to the right place because today we are going to tell you about the complete code of how we made this quiz game and how you can make it. You can

Now the question arises that what happens by making such a project, so friends I want to tell you that when you make such a big level project then you get a very good knowledge of coding which helps you in getting a job because the simple thing is if you make such a project then your skill will improve and you get experience, so let’s go now without delay we will understand our code step by step

HTML (index.html)

First of all, to create our game, we have to make a structure which can only be made with the help of HTML. When we make a structure with the help of HTML, it does not look good at all. To make it look good, we have to use CSS which we will see later, but friends, before that, you need to understand the HTML code properly. So, let’s understand the HTML code.

  • Friends, you know that it is important to have a title in any project, so we have put this title <title>CodeWithCurious.com – Quiz Game</title> You can change it as well
  • As I have just told you that CSS is used to make the project better but before that you need to link CSS with the HTML file which you can do like this <link rel=”stylesheet” href=”style.css” />
  • Then comes the question of icon, you can put it as per your choice <link rel=”icon” href=”…” />
  • <body> This tag is the main part of the HTML, it is important to use it because we write the code of our HTML in it
  • First of all we have created a <div> whose class we have kept container which is i for all
  • In h1 heading we have added a heading in which we have added quiz game text <h1 style=”margin-bottom: 2px;”>Quiz App</h1> you can change it
  • Friends, we have added 20 questions to our game, you can add more <h4 style=”margin-top: 0px;”>20 Questions</h4>
  • Our quiz will be shown to the user with the help of javascript, so we have created a box in HTML <div id=”quiz”></div>Our quiz will be shown to the user with the help of javascript, so we have created a box in HTML <div id=”quiz”></div>
  • To show the result to the user, we have created a <div> box <div id=”result” class=”result”></div> which works with the help of javascript
  • Then we have created a submit button, its work will be done after all the quiz is completed <button id=”submit” class=”button”>Submit</button> On clicking this our scores will be shown
  • If a user is out of the game, then for that we have created a retry button <button id=”retry” class=”button hide”>Retry</button>
  • If user wants to see the answer of quiz, he can see it if he has made a mistake <button id=”showAnswer” class=”button hide”>Show Answer</button> For this we have created a button
  • Friends, this HTML code that we have just seen works on the basis of Javascript, so first of all your Javascript file must be linked to the HTML, so you should use this script tag <script src=”script.js”></script>
				
					

  
    <title>CodeWithCurious.com - Quiz Game</title>
    
    
  
  
    <div class="container">
      <h1 style="margin-bottom: 2px">Quiz App</h1>
      <h4 style="margin-top: 0px">20 Questions</h4>
      <div id="quiz"></div>
      <div id="result" class="result"></div>
      <button id="submit" class="button">Submit</button>
      <button id="retry" class="button hide">Retry</button>
      <button id="showAnswer" class="button hide">Show Answer</button>
    </div>
    
  


				
			

CSS (Style.css)

				
					@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&amp;display=swap");

body {
  font-family: "Poppins", sans-serif;
  background: #b9b3a9;
  display: flex;
  justify-content: center;
}

.container {
  width: 450px;
  padding: 20px;
  margin-top: 80px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 20px;
}

h1 {
  text-align: center;
}
h4 {
  text-align: center;
}

.question {
  font-weight: bold;
  margin-bottom: 10px;
}

.options {
  margin-bottom: 20px;
}

.option {
  display: block;
  margin-bottom: 10px;
}

.button {
  display: inline-block;
  padding: 10px 20px;
  background-color: #428bca;
  color: #fff;
  border: none;
  cursor: pointer;
  font-size: 16px;
  border-radius: 4px;
  transition: background-color 0.3s;
  margin-right: 10px;
}

.button:hover {
  background-color: #3071a9;
}

.result {
  text-align: center;
  margin-top: 20px;
  font-weight: bold;
}

.hide {
  display: none;
}
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&amp;display=swap");

body {
  font-family: "Poppins", sans-serif;
  background: #b9b3a9;
  display: flex;
  justify-content: center;
}

.container {
  width: 450px;
  padding: 20px;
  margin-top: 80px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 20px;
}

h1 {
  text-align: center;
}
h4 {
  text-align: center;
}

.question {
  font-weight: bold;
  margin-bottom: 10px;
}

.options {
  margin-bottom: 20px;
}

.option {
  display: block;
  margin-bottom: 10px;
}

.button {
  display: inline-block;
  padding: 10px 20px;
  background-color: #428bca;
  color: #fff;
  border: none;
  cursor: pointer;
  font-size: 16px;
  border-radius: 4px;
  transition: background-color 0.3s;
  margin-right: 10px;
}

.button:hover {
  background-color: #3071a9;
}

.result {
  text-align: center;
  margin-top: 20px;
  font-weight: bold;
}

.hide {
  display: none;
}

				
			

Javascript (Script.js)

Friends, the code that you are getting to see below is the JavaScript code which is an important part of our game, without it you can make a game but no user can play that game. We have added some questions in our game which are displayed with the help of JavaScript. When a user enters the game, when he starts the game, then he is shown a random question for which the user has to write the answer. The faster he writes the answer, the higher the score he gets and it is also important that the answer is correct.

  • First we target the date of our HTML which is named”main”. const i = document.querySelector(“.i”);
  • We have done the same in the other <div> as well, but friends, we can target only one element with one “id”. If you make some mistake then there can be a problem in running your code.
  • const typeArea = document.querySelector(“.typingArea”);
    const btn = document.querySelector(“.btn”);
  • “Cust Words” We have added some questions using custom words, you can edit them
				
					const quizData = [
  {
    question: "What is the capital of France?",
    options: ["Paris", "London", "Berlin", "Madrid"],
    answer: "Paris",
  },
  {
    question: "What is the largest planet in our solar system?",
    options: ["Mars", "Saturn", "Jupiter", "Neptune"],
    answer: "Jupiter",
  },
  {
    question: "Which country won the FIFA World Cup in 2018?",
    options: ["Brazil", "Germany", "France", "Argentina"],
    answer: "France",
  },
  {
    question: "What is the tallest mountain in the world?",
    options: ["Mount Everest", "K2", "Kangchenjunga", "Makalu"],
    answer: "Mount Everest",
  },
  {
    question: "Which is the largest ocean on Earth?",
    options: [
      "Pacific Ocean",
      "Indian Ocean",
      "Atlantic Ocean",
      "Arctic Ocean",
    ],
    answer: "Pacific Ocean",
  },
  {
    question: "What is the chemical symbol for gold?",
    options: ["Au", "Ag", "Cu", "Fe"],
    answer: "Au",
  },
  {
    question: "Who painted the Mona Lisa?",
    options: [
      "Pablo Picasso",
      "Vincent van Gogh",
      "Leonardo da Vinci",
      "Michelangelo",
    ],
    answer: "Leonardo da Vinci",
  },
  {
    question: "Which planet is known as the Red Planet?",
    options: ["Mars", "Venus", "Mercury", "Uranus"],
    answer: "Mars",
  },
  {
    question: "What is the largest species of shark?",
    options: [
      "Great White Shark",
      "Whale Shark",
      "Tiger Shark",
      "Hammerhead Shark",
    ],
    answer: "Whale Shark",
  },
  {
    question: "Which animal is known as the King of the Jungle?",
    options: ["Lion", "Tiger", "Elephant", "Giraffe"],
    answer: "Lion",
  },
  {
    question: "What is the capital of Japan?",
    options: ["Tokyo", "Kyoto", "Osaka", "Nagoya"],
    answer: "Tokyo",
  },
  {
    question: "Which element has the atomic number 1?",
    options: ["Helium", "Oxygen", "Hydrogen", "Carbon"],
    answer: "Hydrogen",
  },
  {
    question: "Who wrote 'Romeo and Juliet'?",
    options: [
      "Charles Dickens",
      "William Shakespeare",
      "Mark Twain",
      "Leo Tolstoy",
    ],
    answer: "William Shakespeare",
  },
  {
    question: "What is the smallest country in the world?",
    options: ["Monaco", "San Marino", "Liechtenstein", "Vatican City"],
    answer: "Vatican City",
  },
  {
    question: "Which planet is known for its rings?",
    options: ["Venus", "Saturn", "Jupiter", "Neptune"],
    answer: "Saturn",
  },
  {
    question: "Who discovered penicillin?",
    options: [
      "Marie Curie",
      "Alexander Fleming",
      "Louis Pasteur",
      "Isaac Newton",
    ],
    answer: "Alexander Fleming",
  },
  {
    question: "Which continent is the Sahara Desert located on?",
    options: ["Asia", "Africa", "Australia", "Europe"],
    answer: "Africa",
  },
  {
    question: "What is the main ingredient in guacamole?",
    options: ["Tomato", "Avocado", "Onion", "Pepper"],
    answer: "Avocado",
  },
  {
    question: "Which country is known as the Land of the Rising Sun?",
    options: ["China", "South Korea", "Thailand", "Japan"],
    answer: "Japan",
  },
];

const quizContainer = document.getElementById("quiz");
const resultContainer = document.getElementById("result");
const submitButton = document.getElementById("submit");
const retryButton = document.getElementById("retry");
const showAnswerButton = document.getElementById("showAnswer");

let currentQuestion = 0;
let score = 0;
let incorrectAnswers = [];

function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
}

function displayQuestion() {
  const questionData = quizData[currentQuestion];

  const questionElement = document.createElement("div");
  questionElement.className = "question";
  questionElement.innerHTML = `${currentQuestion + 1}.${questionData.question}`;

  const optionsElement = document.createElement("div");
  optionsElement.className = "options";

  const shuffledOptions = [...questionData.options];
  shuffleArray(shuffledOptions);

  for (let i = 0; i < shuffledOptions.length; i++) {
    const option = document.createElement("label");
    option.className = "option";

    const radio = document.createElement("input");
    radio.type = "radio";
    radio.name = "quiz";
    radio.value = shuffledOptions[i];

    const optionText = document.createTextNode(shuffledOptions[i]);

    option.appendChild(radio);
    option.appendChild(optionText);
    optionsElement.appendChild(option);
  }

  quizContainer.innerHTML = "";
  quizContainer.appendChild(questionElement);
  quizContainer.appendChild(optionsElement);
}

function checkAnswer() {
  const selectedOption = document.querySelector('input[name="quiz"]:checked');
  if (selectedOption) {
    const answer = selectedOption.value;
    if (answer === quizData[currentQuestion].answer) {
      score++;
    } else {
      incorrectAnswers.push({
        question: quizData[currentQuestion].question,
        incorrectAnswer: answer,
        correctAnswer: quizData[currentQuestion].answer,
      });
    }
    currentQuestion++;
    selectedOption.checked = false;
    if (currentQuestion < quizData.length) {
      displayQuestion();
    } else {
      displayResult();
    }
  }
}

function displayResult() {
  quizContainer.style.display = "none";
  submitButton.style.display = "none";
  retryButton.style.display = "inline-block";
  showAnswerButton.style.display = "inline-block";
  resultContainer.innerHTML = `You scored ${score} out of ${quizData.length}!`;
}

function retryQuiz() {
  currentQuestion = 0;
  score = 0;
  incorrectAnswers = [];
  quizContainer.style.display = "block";
  submitButton.style.display = "inline-block";
  retryButton.style.display = "none";
  showAnswerButton.style.display = "none";
  resultContainer.innerHTML = "";
  displayQuestion();
}

function showAnswer() {
  quizContainer.style.display = "none";
  submitButton.style.display = "none";
  retryButton.style.display = "inline-block";
  showAnswerButton.style.display = "none";

  let incorrectAnswersHtml = "";
  for (let i = 0; i < incorrectAnswers.length; i++) {
    incorrectAnswersHtml += `
        <p>
          <strong>Question:</strong> ${incorrectAnswers[i].question}<br>
          <strong>Your Answer:</strong> ${incorrectAnswers[i].incorrectAnswer}<br>
          <strong>Correct Answer:</strong> ${incorrectAnswers[i].correctAnswer}
        </p>
      `;
  }

  resultContainer.innerHTML = `
      <p>You scored ${score} out of ${quizData.length}!</p>
      <p>Incorrect Answers:</p>
      ${incorrectAnswersHtml}
    `;
}

submitButton.addEventListener("click", checkAnswer);
retryButton.addEventListener("click", retryQuiz);
showAnswerButton.addEventListener("click", showAnswer);

displayQuestion();
				
			
Your download is starting now...

Output:

Build a Quiz Game Using HTML CSS & JavaScript

Disclaimer: The code provided in this post is sourced from GitHub and is distributed under the MIT License. All credits for the original code go to the respective owner. We have shared this code for educational purposes only. Please refer to the original repository for detailed information and any additional usage rights or restrictions.

Build a Quiz Game Using HTML CSS and JavaScript Introduction Hello friends, welcome to today’s new blog. Today’s project is going to …

Number Guessing Game Using HTML CSS And JavaScript Introduction Hello coders, you might have played various games, but were you aware that …

Emoji Catcher Game Using HTML CSS and JavaScript Introduction Hello Coders, Welcome to another new blog. In this article we’ve made a …

Typing Challenge Using HTML CSS and JavaScript Introduction Hello friends, all you developer friends are welcome to our new project. If you …

Get Huge Discounts
More Python Projects