How to Build a Quiz App with HTML, CSS and JavaScript

How to Build a Quiz App with HTML, CSS, and JavaScript

In this tutorial, we will guide you through the process of building a quiz app using HTML, CSS, and JavaScript. We will cover the following topics:

  1. Setting up the basic HTML structure
  2. Styling the app with CSS
  3. Creating the quiz questions and answers
  4. Implementing the scoring system and feedback
  5. Adding interactivity with JavaScript

By the end of this tutorial, you will have a fully functional quiz app that you can customize and use for your own purposes.

Prerequisites

Before we begin, make sure you have the following:

  • Basic knowledge of HTML, CSS, and JavaScript
  • A code editor of your choice

Setting up the basic HTML structure

To start building our quiz app, we need to set up the basic HTML structure. Open your code editor and create a new HTML file. Let’s name it index.html.

In the index.html file, start by adding the HTML doctype declaration and the opening and closing <html> tags. Inside the <html> tags, add the <head> and <body> tags.

<!DOCTYPE html>
<html>
<head>
  <title>Quiz App</title>
</head>
<body>

</body>
</html>

Inside the <body> tag, add a <header> element to hold the title of the quiz app.

<body>
  <header>
    <h1>Quiz App</h1>
  </header>
</body>

Next, we will add a container to hold the quiz questions and answers. Add a <div> element with the class name container. Inside the container, we will add the quiz questions and answers dynamically using JavaScript.

<body>
  <header>
    <h1>Quiz App</h1>
  </header>

  <div class="container">

  </div>
</body>

Styling the app with CSS

Now that we have set up the basic HTML structure, let’s style our quiz app using CSS. Create a new CSS file called style.css and link it to your HTML file by adding the following <link> tag inside the <head> tag of index.html.

<!DOCTYPE html>
<html>
<head>
  <title>Quiz App</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <!-- HTML code goes here -->
</body>
</html>

Inside style.css, let’s start by adding some basic styles to our app. We will center align the text, set a maximum width for the container, and add some padding and margin to give it some spacing.

body {
  text-align: center;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

Save both index.html and style.css files and open index.html in your web browser. You should see the app title centered on the page with some spacing around it.

Creating the quiz questions and answers

Now that we have set up the basic structure and styling of our app, let’s move on to creating the quiz questions and answers.

Inside the container <div> tag, add a <div> element with a class name of question. This element will display the current quiz question.

<div class="container">
  <div class="question">

  </div>
</div>

Inside the question <div>, add an <h2> tag to display the question text.

<div class="container">
  <div class="question">
    <h2>Question Text</h2>
  </div>
</div>

Next, we will add the answer options for each question. Inside the question <div>, add a <ul> element to hold the answer options.

<div class="container">
  <div class="question">
    <h2>Question Text</h2>
    <ul class="options">

    </ul>
  </div>
</div>

Inside the options <ul>, add a <li> element for each answer option. Add a <label> element inside each <li>, followed by an <input type="radio"> element. The <label> will display the answer text, and the <input> will allow users to select an answer.

<div class="container">
  <div class="question">
    <h2>Question Text</h2>
    <ul class="options">
      <li>
        <label>
          <input type="radio">
          Answer 1
        </label>
      </li>
      <li>
        <label>
          <input type="radio">
          Answer 2
        </label>
      </li>
      <li>
        <label>
          <input type="radio">
          Answer 3
        </label>
      </li>
      <li>
        <label>
          <input type="radio">
          Answer 4
        </label>
      </li>
    </ul>
  </div>
</div>

Save your changes and preview index.html in your web browser. You should see a question with four answer options displayed on the page.

Implementing the scoring system and feedback

Now that we have created the quiz questions and answers, let’s implement the scoring system and feedback mechanism.

First, we need to keep track of the user’s selected answer for each question. Add a new <script> tag at the bottom of index.html to add JavaScript code to handle the quiz functionality.

<script src="script.js"></script>
</body>
</html>

Next, create a new JavaScript file called script.js. This is where we will write the JavaScript code to handle the quiz functionality.

Inside script.js, let’s start by defining an array of objects to store the quiz questions and answer options. Each object in the array will represent a question and its associated answer options.

const quizData = [
  {
    question: "Question 1",
    options: ["Answer 1", "Answer 2", "Answer 3", "Answer 4"],
    answer: 1
  },
  {
    question: "Question 2",
    options: ["Answer 1", "Answer 2", "Answer 3", "Answer 4"],
    answer: 2
  },
  // Add more questions here
];

You can customize the number of questions, answer options, and correct answers to fit your specific quiz requirements.

Next, we will use JavaScript to dynamically populate the quiz questions and answer options inside the HTML. Add the following code to the script.js file.

const questionContainer = document.querySelector(".question");
const optionsContainer = document.querySelector(".options");
let currentQuestion = 0;

function showQuestion() {
  const question = quizData[currentQuestion];
  questionContainer.innerHTML = `<h2>${question.question}</h2>`;

  let optionsHtml = "";
  question.options.forEach((option, index) => {
    optionsHtml += `
      <li>
        <label>
          <input type="radio" name="option" value="${index}">
          ${option}
        </label>
      </li>
    `;
  });

  optionsContainer.innerHTML = optionsHtml;
}

showQuestion();

The showQuestion() function retrieves the current question object from the quizData array and dynamically updates the HTML with the question and answer options.

Save your changes and preview index.html in your web browser. You should see the first question and its answer options displayed on the page.

Adding interactivity with JavaScript

Now that we have populated the quiz questions and answer options, let’s add some interactive elements and functionality.

First, we need to add a button to the bottom of the quiz page to allow users to submit their answers.

Inside the container <div>, add a <div> element with a class name of actions. Inside the actions <div>, add a <button> element with the text “Submit”.

<div class="container">
  <div class="question">
    <h2>Question Text</h2>
    <ul class="options">
      <!-- Answer options go here -->
    </ul>
  </div>

  <div class="actions">
    <button class="submit">Submit</button>
  </div>
</div>

Next, let’s add the JavaScript code to handle the submission of answers and display the feedback to the user.

Inside script.js, add the following code.

const submitButton = document.querySelector(".submit");
let score = 0;

submitButton.addEventListener("click", () => {
  const selectedOption = optionsContainer.querySelector("input[name='option']:checked");

  if (selectedOption) {
    const selectedAnswer = parseInt(selectedOption.value);

    if (selectedAnswer === quizData[currentQuestion].answer) {
      score++;
    }

    currentQuestion++;

    if (currentQuestion < quizData.length) {
      showQuestion();
    } else {
      showResult();
    }
  }
});

function showResult() {
  questionContainer.innerHTML = `<h2>You have completed the quiz!</h2>`;
  optionsContainer.innerHTML = `<p>Your score: ${score}/${quizData.length}</p>`;
}

The event listener is attached to the submit button, and when clicked, it retrieves the selected answer option and checks if it matches the correct answer. If the answer is correct, the score is incremented by one.

The currentQuestion variable is then incremented, and if there are remaining questions, the showQuestion() function is called to display the next question. If there are no more questions, the showResult() function is called to display the final score.

Save your changes and preview index.html in your web browser. You should be able to submit answers and see the score and completion message at the end of the quiz.

Conclusion

Congratulations! You have successfully built a quiz app using HTML, CSS, and JavaScript. You can further customize the app by adding more quiz questions and answer options, styling the app to match your branding, and adding additional features like timers or leaderboards.

Feel free to experiment with the code and add your own creative touches to the quiz app. Happy coding!

Related Post