Best Quiz Game Using HTML CSS And JavaScript

Introduction
Hello coders, welcome to another new blog. Today in this article we’ll learn to create a Quiz Game. This quiz game will generate some question with options and we’ve answer those questions. When quiz ends, it’ll show our score that how much answer we’ve given right. This game is interesting and good project.
To create our quiz game project, we’ve used HTML CSS and JavaScript. Using these 3 technologies we’ve made our Quiz Game. The HTML code set up the basic structure for our game and CSS designs our Quiz Game. The JavaScript adds functionality in our Quiz game and make it interactive.
If you also want to create this type of game then you just need skills in HTML CSS and JavaScript. If you’re good in these technologies then you’re good to go. You can easily create this type of Games by yourself. Each project enhances and improves our coding skills and knowledge. Let’s understand the code.
HTML (index.html)
Get Discount on Top Educational Courses
This is our HTML code which sets up the basic structure for our Game. It build basic element of our Quiz Game. HTML links all the external files which adds interactivity in our game. Let’s breakdown the code.
- <!DOCTYPE html> : This defines the type of our document and ensure it is a HTML code file.
- <title> : It sets title of our webpage as Quiz Game.
- <link> : This tag links external CSS file into our code.
- <body> : It contains all content of our game.
- <div class =”container”> : It contains all the game data and works as container.
- <h1> : This will display a heading at the top and it contains a margin bottom of 2px using inline CSS.
- <h4> : This displays the number of questions.
- <div id=”quiz”> : This will contains all the quiz questions.
- <div id =”result”> : This will show the result after completing the quiz.
- <button id=”submit”>: This is for submit the answer.
- <button id=”retry”>: This is for retry the test.
- <button id=”showAnswer”> : This button will show the answer.
- <script> : This tag links external JavaScript file into our code.
CodeWithCurious.com - Quiz Game
Quiz App
20 Questions
CSS (Style.css)
This is our CSS code which designs our Quiz game. This CSS code make our quiz game visually appealing and interactive. CSS stands for Cascading Style Sheet. Let’s breakdown the code.
- The code starts by importing the external google font “Poppins”.
- Body sets display flex and horizontally centers the element. It sets font family and lightgray background.
- The .container sets width of 450px, 20px of padding, 80px of margin-top, white background color with some box shadow.
- H1 and h4 centers the text using text-align property.
- .question sets it font weight bold and margin.
- 20px of margin bottom set to .options and display block to .option .
- The .button class sets display as inline-block, removes the border, set padding, cursor as pointer, background color of light blue, border radius and some transition properties. The text color is set to white. On the button hover we’ve changed it’s background color.
- .result class aligns the text center and set the font weight to bold with 20px of margin from the top.
- .hide sets display none.
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&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)
This is our JavaScript code which adds functionality in our game. This code is the main part of our game as it adds interactive functionality to our game. Using this code we’ve made our game interactive. JavaScript code adds logic to our game. Let’s understand the code.
- The code starts with a array called quizData which contains multiple object and each object contains a question, option and answers.
- We accessed the essential element from the HTML using DOM and stored them in variables.
- Then, we initialise 3 variable that are currentQuestion, score and incorrectAnswer. The first 2 variable initialise with 0 and last one assigns a empty array.
- The shuffleArray function takes arrays as input and shuffle the array randomly. This will shuffle the order of answer options for each question.
- The displayQuestion function render the current question and its answer on the page. It takes the question data from the quizData. Then it creates HTML element to display the question and append them to quizContainer.
- The checkAnswer function will check the answer of user. It retrieves the selected quiz. Then it compares the selected answer with correct answer in quizData, and increments the score or adds the question to the incorrectAnswers array accordingly.
- The displayResult function is called when all questions have been answered. It hides the quiz container and submit button and shows the retry and show answer buttons. It displays users score.
- The retryQuiz function starts the quiz again. It resets all the variables. It displays the quiz container and submit button and hide the retry and show answer buttons. Then it calls displayQuestion function.
- The showAnswer function displays the answers. It hides quiz container, submit button and show answer button. It only shows the retry button. It generates HTML to display the player’s score and lists all the incorrect answers with the corresponding correct answers.
- Event listeners are added to the submit, retry and showAnswer button. On click, their respective function will run.
- At last we call the displayQuestion function.
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 += `
Question: ${incorrectAnswers[i].question}
Your Answer: ${incorrectAnswers[i].incorrectAnswer}
Correct Answer: ${incorrectAnswers[i].correctAnswer}
`;
}
resultContainer.innerHTML = `
You scored ${score} out of ${quizData.length}!
Incorrect Answers:
${incorrectAnswersHtml}
`;
}
submitButton.addEventListener("click", checkAnswer);
retryButton.addEventListener("click", retryQuiz);
showAnswerButton.addEventListener("click", showAnswer);
displayQuestion();
Output:

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.
MathGenius Pro – AI-Powered Math Solver Using Python Introduction: From simple arithmetic to more complicated college-level subjects like integration, differentiation, algebra, matrices, …
CipherMaze: The Ultimate Code Cracking Quest Game Using Python Introduction: You can make CipherMaze, a fun and brain-boosting puzzle game, with Python …
Warp Perspective Using Open CV Python Introduction: In this article, we are going to see how to Create a Warp Perspective System …
Custom AI Story Generator With Emotion Control Using Python Introduction: With the help of this AI-powered story generator, users can compose stories …