Projects

Building a JavaScript Quiz Game

Introduction to the JavaScript Quiz Game

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.

Setting Up Your Workspace

Creating Your Project Folder and Files

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.

Step 1: Create Your Project Folder

Create a new folder on your computer to store all your project files. You can name it "javascript-quiz-game".

On Windows:
  1. Right-click on your desktop.
  2. Choose "New" > "Folder".
  3. Name it "javascript-quiz-game".
On Mac:
  1. Right-click on your desktop.
  2. Choose "New Folder".
  3. Name it "javascript-quiz-game".

Step 2: Get Your Text Editor Ready

You'll need a text editor to write your code. We recommend Visual Studio Code, which is free and beginner-friendly.

  1. Download Visual Studio Code from code.visualstudio.com.
  2. Install it on your computer.
  3. Open VS Code and drag your "javascript-quiz-game" folder into the window.

Step 3: Create Your Project Files

We need three essential files for our project:

To create these files:

  1. Open VS Code.
  2. index.html - Click "New File" and save it as "index.html".
  3. styles.css - Click "New File" again and save it as "styles.css".
  4. script.js - Click "New File" once more and save it as "script.js".

🎯 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.

Setting Up the HTML Structure

Creating the Quiz Game HTML

Let's start by building the HTML structure for our quiz game. HTML is like the foundation of our app.

  1. 1. Open "index.html": Open your "index.html" file in your code editor.
  2. 2. Add the Quiz Game HTML: Copy and paste the following code into your "index.html" file:
    <!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:

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!

Styling the Quiz Game

Adding CSS Styles

CSS is like the paint and brushes we use to make our app visually appealing. Let's add some styles to our quiz game.

  1. 1. Open "styles.css": Open the "styles.css" file in your code editor.
  2. 2. Add Quiz Game Styles: Copy and paste the following CSS code into your "styles.css" file:
    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:

Save your "styles.css" file. Now, if you open "index.html" in a web browser, you'll see the styled quiz game.

Adding JavaScript for User Interactions

Selecting HTML Elements

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.

  1. 1. Open "script.js": Open the "script.js" file in your code editor.
  2. 2. Selecting Elements: Copy and paste the following JavaScript code into your "script.js" file:
    // 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.

Defining Quiz Data

Next, we'll define the quiz data. This will include the questions and their corresponding answers.

  1. 3. Defining Quiz Data: Copy and paste the following JavaScript code into your "script.js" file:
    // 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 correctproperty.

Function to Start the Quiz

Now, let's create a function to start the quiz. This function will initialize the quiz and show the first question.

  1. 4. Function to Start the Quiz: Copy and paste the following JavaScript code into your "script.js" file:
    // 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.

Function to Show the Current Question

Next, let's create a function to show the current question. This function will display the question and its answer options.

  1. 5. Function to Show the Current Question: Copy and paste the following JavaScript code into your "script.js" file:
    // 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.

Function to Reset the State of the Quiz

Now, let's create a function to reset the state of the quiz. This function will remove all answer buttons from the previous question.

  1. 6. Function to Reset the State of the Quiz: Copy and paste the following JavaScript code into your "script.js" file:
    // 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.

Function to Handle Answer Selection

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.

  1. 7. Function to Handle Answer Selection: Copy and paste the following JavaScript code into your "script.js" file:
    // 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.

Function to Show the Results

Now, let's create a function to show the results. This function will display the final score.

  1. 8. Function to Show the Results: Copy and paste the following JavaScript code into your "script.js" file:
    // 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.

Function to Handle the Next Button Click

Finally, let's create a function to handle the next button click. This function will move to the next question.

  1. 9. Function to Handle the Next Button Click: Copy and paste the following JavaScript code into your "script.js" file:
    // 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.

Event Listeners

Now, let's add event listeners to the start button and next button to handle user interactions.

  1. 10. Event Listeners: Copy and paste the following JavaScript code into your "script.js" file:
    // 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.

Initial State

Finally, let's set the initial state of the quiz.

  1. 11. Initial State: Copy and paste the following JavaScript code into your "script.js" file:
    // 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.

Making the Quiz Game Responsive

Making the Quiz Game Responsive

Let's ensure our quiz game looks great on various devices by adding responsive design using CSS media queries.

  1. 1. Open "styles.css": Open the "styles.css" file in your code editor.
  2. 2. Add Responsive Design Styles: Copy and paste the following CSS code into your "styles.css" file:
    @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:

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.

Final Thoughts

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! 🚀