JavaScript Animal Quiz Game

RMAG news

Intro: This is a small HTML, JavaScript Quiz Game for JavaScript Beginners. I’ve commented on each line of the JavaScript file to help myself and anyone new to JavaScript understand what each line does. Feel free to correct me if I’ve made mistakes and you can also copy the code and tweak it to your liking.

The first code block is HTML, second is CSS and third is JavaScript.

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>Animal Quiz</title>
<link rel=”stylesheet” href=”quiz.css”>
</head>
<body>
<div id=”quiz”>
<h1>Guess the Animal</h1>
<div id=”questionImage”>
<img src=”” id=”questionImg” alt=”Question Image” style=”width:300px; height:auto;”>
</div>
<div id=”question”></div>
<input type=”text” id=”answer” placeholder=”Type your answer here…”>
<button id =”button” onclick=”submitAnswer()”>Submit</button>
<div id=”feedback”></div>
<div id=”score”></div>
</div>
<script src=”quiz.js”></script>
</body>
</html>
/* styles.css */
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f4f4f9;
}

#quiz {
text-align: center;
border: 2px solid #ddd;
padding: 20px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
background-color: white;
width: 300px;
}

input[type=”text”] {
width: calc(100% – 22px);
padding: 10px;
margin-top: 8px;
margin-bottom: 8px;
}

button {
padding: 10px 20px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
}

img{
width: 50%;
height: 50%;
}

#score{
padding-top: 10px;
}

.popup {
position: fixed;
top: 60%;
left: 50%;
transform: translate(-50%, -50%);
background-color: lightgreen;
background-image: url(‘C:/Users/petix/Downloads/thumbs_up.jpg’);
background-size: 100% 100%;
padding-top: 80px;
z-index: 1000;
text-align: center;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0,0,0,0.1); /* Full cover from the left */
width: 18%; /* Full width */
height: 36%;
font-size: 20px;
font-weight: bold;
}

.popup button {
padding: 10px 20px;
font-size: 16px;
color: white;
background-color: #4CAF50;
border: none;
border-radius: 5px;
cursor: pointer;
margin-top: 10px;
}

.popup.wrong-answer {
background-image: url(‘C:/Users/petix/OneDrive/Desktop/my_javascript_games/animal_quiz/thumbs_down.jpg’);
}

// quiz.js

//three variables are created
//one holds the score, another holds the number of user attempts and the last one checks if the user is still guessing
let score = 0;
let attempt = 0;
let still_guessing = true;

//an array is created and it holds three objects
//those objects the quiz questions
let questions = [
{
question: “Which bear lives at the North Pole?”,
answer: “polar bear”,
image: “C:/Users/petix/Downloads/polar_bear.jpg”
},
{
question: “What is the fastest mammal?”,
answer: “cheetah”,
image: “C:/Users/petix/Downloads/cheetah.jpg”
},
{
question: “What is the largest animal in the world?”,
answer: “blue whale”,
image: “C:/Users/petix/Downloads/blue_whale.jpg”
},
{
question: “What is the tallest land animal in the world?”,
answer: “giraffe”,
image: “C:/Users/petix/Downloads/giraffe.jpg”
},
{
question: “What is the only mammal that can fly?”,
answer: “bat”,
image: “C:/Users/petix/Downloads/bat.jpg”
}
];

//this variable holds the current question number
let currentQuestion = 0;

//this line makes displays the current question in the question div
document.getElementById(‘question’).innerText = questions[currentQuestion].question;

//a function called submitAnswer is created
function submitAnswer() {
//the userAnswer variable gets the answer of the user from the input
let userAnswer = document.getElementById(‘answer’).value;
//if still_guessing is still true and number of attempts is less than three
if (still_guessing && attempt < 3) {
//if the value of userAnswer is equal to the answer of the currentQuestion
if (userAnswer.toLowerCase() === questions[currentQuestion].answer.toLowerCase()) {
console.log(questions[currentQuestion].answer.toLowerCase());
//Show this message in the feedback div
document.getElementById(‘feedback’).innerText = ‘Correct Answer!’;
//add 1 to the value of score
score++;
//display the score in the score div
document.getElementById(‘score’).innerHTML = ‘Score: ‘ + score;
// Show popup for correct answer with a button to proceed
showPopup(‘Correct!’);
//if the user’s answer is incorrect
} else {
//if the value of attempt is less than 2
if (attempt < 2) {
//display this message on the feedback div
document.getElementById(‘feedback’).innerText = ‘Sorry wrong answer. Try again.’;
//add one to the value of attempt
attempt++;
console.log(attempt);
//if the value of attempt is no longer less than 2
} else {
//call the showPopup function with this message as the first argument and set the second argument to true
showPopup(`Correct answer is ${questions[currentQuestion].answer.toUpperCase()}.`, true);
//document.getElementById(‘button’).disabled = true;
}
}
}
}

// Add event listener to the input field to detect Enter key press
document.getElementById(‘answer’).addEventListener(‘keyup’, function(event) {
if (event.key === ‘Enter’) {
submitAnswer();
}
});

// Function to update question and image
function updateQuestionAndImage() {
//if the value of currentQuestion is less than the number of objects in questions
if (currentQuestion < questions.length) {
//display a question
document.getElementById(‘question’).innerText = questions[currentQuestion].question;
//display an image
document.getElementById(‘questionImg’).src = questions[currentQuestion].image; // Set image source
//the value of the answer div will now be ”
document.getElementById(‘answer’).value = ”;
//the value of the feedback div will now be ”
document.getElementById(‘feedback’).innerText = ”;
}
}

// Display the first question and image when the page loads
updateQuestionAndImage();

//create nextQuestion() function
function nextQuestion() {
//for the next question the attempt must be set to zero
attempt = 0;
//add one to the value of currentQuestion
currentQuestion++;
//if the value of currentQuestion is less than the number of objects in questions array
if (currentQuestion < questions.length) {
//call updateQuestionAndImage function
updateQuestionAndImage();
//if the value of currentQuestion is not less than the number of objects in questions array
} else {
//display this
document.getElementById(‘quiz’).innerHTML = `<h1>Quiz Completed</h1>Your score is ${score}/${questions.length}`;
}
}

//create a function called showPopup with two parameters
//one is the message to be displayed on the popup
//the other takes a bolean value – false
function showPopup(message, isWrongAnswer = false) {
// Create a new div element and store it in popup
let popup = document.createElement(‘div’);
//give the div a class name – popup
popup.className = ‘popup’; // Add the class name to the popup
//the content on the popup will be the message’s value
popup.textContent = message;

//if the value of isWrongAnswer is now true
if(isWrongAnswer) {
//add wrong-answer to the popup div
popup.classList.add(‘wrong-answer’);
}

popup.appendChild(document.createElement(‘br’));
document.body.appendChild(popup);

setTimeout(() => {
if (document.body.contains(popup)) {
document.body.removeChild(popup);
nextQuestion();
}
}, 1100);
}

//display this text in the score div
document.getElementById(‘score’).innerText = `Score: ${score}`;