Welcome to the beginner-friendly tutorial on building a JavaScript Quiz Game! In this project, we'll create a fun quiz game where users can answer multiple-choice questions. This project is an excellent way to learn how to use arrays and functions to manage questions, track scores, and display results.
Before we begin coding, let's set up a workspace for our project. This folder will be your digital canvas, where you'll keep all the project files organized.
Create a new folder on your computer to store all your project files. You can name it "javascript-quiz-game".
On Windows:You'll need a text editor to write your code. We recommend Visual Studio Code, which is free and beginner-friendly.
We need three essential files for our project:
To create these files:
🎯 Success Check: You should now have:
👉 Tip: If something's not working, try restarting VS Code or creating the files using the "File → New File" menu.
Let's start by building the HTML structure for our quiz game. HTML is like the foundation of our app.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Quiz Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>JavaScript Quiz Game</h1>
<div id="quiz-container">
<div id="question-container" class="hide">
<div id="question">Question</div>
<div id="answer-buttons" class="button-grid"></div>
</div>
<div id="controls">
<button id="start-btn" class="start-btn">Start Quiz</button>
<button id="next-btn" class="next-btn hide">Next</button>
</div>
<div id="results" class="hide">
<h2>Results</h2>
<p id="score">Score: 0</p>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Let's break down the HTML structure:
<div class="container">
: The main container for our app.<h1>JavaScript Quiz Game</h1>
: The title of our app.<div id="quiz-container">
: The container for the quiz.<div id="question-container" class="hide">
: The container for the question and answer buttons.<div id="question">
: The element for displaying the question.<div id="answer-buttons" class="button-grid">
: The container for the answer buttons.<div id="controls">
: The container for the start and next buttons.<button id="start-btn" class="start-btn">Start Quiz</button>
: The button to start the quiz.<button id="next-btn" class="next-btn hide">Next</button>
: The button to move to the next question.<div id="results" class="hide">
: The container for displaying the results.<p id="score">Score: 0</p>
: The element for displaying the score.<script src="script.js"></script>
: Includes the JavaScript file for handling the app's functionality.Save your "index.html" file. Now we have the basic HTML structure in place. In the next step, we'll add some styling to make it look nice!
CSS is like the paint and brushes we use to make our app visually appealing. Let's add some styles to our quiz game.
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
box-sizing: border-box;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 400px;
text-align: center;
}
h1 {
margin: 0 0 20px;
font-size: 1.5rem;
}
#quiz-container {
display: flex;
flex-direction: column;
align-items: center;
}
#question-container {
margin-bottom: 20px;
text-align: left;
width: 100%;
}
#question {
font-size: 1.2rem;
margin-bottom: 10px;
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
width: 100%;
}
.button-grid button {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
transition: background-color 0.3s ease;
}
.button-grid button:hover {
background-color: #0056b3;
}
#controls {
margin-top: 20px;
}
#controls button {
background-color: #007bff;
color: #fff;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
transition: background-color 0.3s ease;
}
#controls button:hover {
background-color: #0056b3;
}
#results {
margin-top: 20px;
text-align: center;
}
#score {
font-size: 1.2rem;
margin-top: 10px;
}
.hide {
display: none;
}
Let's understand the CSS rules we just added:
body
: Sets the default font, removes margins and padding, and centers the content on the screen..container
: Styles the container with a white background, padding, rounded corners, and a shadow.h1
: Styles the title with a larger font size and margin.#quiz-container
: Styles the quiz container with flexbox for layout.#question-container
: Adds margin and text alignment for better readability.#question
: Styles the question with a larger font size and margin..button-grid
: Uses grid layout to arrange answer buttons..button-grid button
: Styles the answer buttons with a blue background, white text, no border, padding, border-radius, cursor, and transition for smooth changes.#controls
: Adds margin to the control buttons.#controls button
: Styles the start and next buttons.#results
: Styles the results container with margin and text alignment.#score
: Styles the score text with a larger font size and margin..hide
: Hides elements that should not be visible initially.Save your "styles.css" file. Now, if you open "index.html" in a web browser, you'll see the styled quiz game.
First, we need to select the HTML elements we want to work with. We'll select the question container, answer buttons, start button, next button, and score element.
// Selecting HTML elements
const startBtn = document.getElementById('start-btn');
const nextBtn = document.getElementById('next-btn');
const questionContainer = document.getElementById('question-container');
const questionElement = document.getElementById('question');
const answerButtonsElement = document.getElementById('answer-buttons');
const resultsContainer = document.getElementById('results');
const scoreElement = document.getElementById('score');
Here, we're using the getElementById
method to select the HTML elements with specific IDs.
Next, we'll define the quiz data. This will include the questions and their corresponding answers.
// Quiz data
const questions = [
{
question: 'What is the capital of France?',
answers: [
{ text: 'Paris', correct: true },
{ text: 'Berlin', correct: false },
{ text: 'Madrid', correct: false },
{ text: 'Rome', correct: false },
],
},
{
question: 'What is 2 + 2?',
answers: [
{ text: '3', correct: false },
{ text: '4', correct: true },
{ text: '5', correct: false },
{ text: '6', correct: false },
],
},
{
question: 'What is the largest planet in our solar system?',
answers: [
{ text: 'Mars', correct: false },
{ text: 'Jupiter', correct: true },
{ text: 'Saturn', correct: false },
{ text: 'Neptune', correct: false },
],
},
];
let currentQuestionIndex = 0;
let score = 0;
Here, we define an array of questions, each with a question and an array of answers. Each answer has a text
and a correct
property.
Now, let's create a function to start the quiz. This function will initialize the quiz and show the first question.
// Function to start the quiz
function startQuiz() {
currentQuestionIndex = 0;
score = 0;
nextBtn.classList.add('hide');
questionContainer.classList.remove('hide');
resultsContainer.classList.add('hide');
showQuestion();
}
In this function, we reset the current question index and score, hide the next button, show the question container, hide the results container, and call the showQuestion
function to display the first question.
Next, let's create a function to show the current question. This function will display the question and its answer options.
// Function to show the current question
function showQuestion() {
resetState();
const currentQuestion = questions[currentQuestionIndex];
questionElement.innerText = currentQuestion.question;
currentQuestion.answers.forEach((answer) => {
const button = document.createElement('button');
button.innerText = answer.text;
button.classList.add('btn');
if (answer.correct) {
button.dataset.correct = true;
}
button.addEventListener('click', selectAnswer);
answerButtonsElement.appendChild(button);
});
}
In this function, we call the resetState
function to reset the state of the quiz, set the question text, and create answer buttons for each answer. We also add an event listener to each button to handle answer selection.
Now, let's create a function to reset the state of the quiz. This function will remove all answer buttons from the previous question.
// Function to reset the state of the quiz
function resetState() {
while (answerButtonsElement.firstChild) {
answerButtonsElement.removeChild(answerButtonsElement.firstChild);
}
}
In this function, we remove all child elements from theanswerButtonsElement
to reset the state for the next question.
Next, let's create a function to handle answer selection. This function will check if the selected answer is correct, update the score, and handle the next question or show the results.
// Function to handle answer selection
function selectAnswer(e) {
const selectedButton = e.target;
const correct = selectedButton.dataset.correct;
if (correct) {
selectedButton.classList.add('correct');
score++;
} else {
selectedButton.classList.add('incorrect');
}
Array.from(answerButtonsElement.children).forEach((button) => {
if (button.dataset.correct) {
button.classList.add('correct');
}
button.disabled = true;
});
if (questions.length > currentQuestionIndex + 1) {
nextBtn.classList.remove('hide');
} else {
showResults();
}
}
In this function, we check if the selected answer is correct, update the score, and add the appropriate class to the button. We also disable all buttons and show the next button if there are more questions, or show the results if it's the last question.
Now, let's create a function to show the results. This function will display the final score.
// Function to show the results
function showResults() {
questionContainer.classList.add('hide');
resultsContainer.classList.remove('hide');
scoreElement.innerText = `Score: ${score}/${questions.length}`;
}
In this function, we hide the question container, show the results container, and update the score text.
Finally, let's create a function to handle the next button click. This function will move to the next question.
// Function to handle the next button click
function handleNextButton() {
currentQuestionIndex++;
showQuestion();
}
In this function, we increment the current question index and call theshowQuestion
function to display the next question.
Now, let's add event listeners to the start button and next button to handle user interactions.
// Event listeners
startBtn.addEventListener('click', startQuiz);
nextBtn.addEventListener('click', handleNextButton);
In this section, we add event listeners to the start button and next button to call the appropriate functions when they are clicked.
Finally, let's set the initial state of the quiz.
// Initial state
startBtn.classList.remove('hide');
nextBtn.classList.add('hide');
resultsContainer.classList.add('hide');
In this section, we ensure that the start button is visible, the next button is hidden, and the results container is hidden initially.
Let's ensure our quiz game looks great on various devices by adding responsive design using CSS media queries.
@media (max-width: 600px) {
.container {
width: 90%;
}
#question {
font-size: 1rem;
}
.button-grid button {
padding: 8px 16px;
font-size: 0.9rem;
}
#controls button {
padding: 8px 16px;
font-size: 0.9rem;
}
#score {
font-size: 1rem;
}
}
Let's understand the CSS rules we just added:
@media (max-width: 600px)
: A media query for screens up to 600px wide (e.g., mobile phones)..container
: Adjusts the width of the container to 90% for better visibility on smaller screens.#question
: Adjusts the font size of the question for better readability on smaller screens..button-grid button
: Adjusts the padding and font size of the answer buttons for better readability on smaller screens.#controls button
: Adjusts the padding and font size of the control buttons for better readability on smaller screens.#score
: Adjusts the font size of the score for better readability on smaller screens.Save your "styles.css" file. Now, if you resize your browser window or view the quiz game on different devices, you'll see the layout adapt to different screen sizes.
Congratulations! You've completed the JavaScript Quiz Game project. You've learned how to create a fun quiz game where users can answer multiple-choice questions. This project introduced you to using arrays and functions to manage questions, track scores, and display results.
Feel free to customize and expand your quiz game further. You can add more questions, improve the design, or even create a mobile version. Happy coding and exploring the world of web development! 🚀