Coastal Media Brand

This tutorial is the perfect way to learn some important JavaScript concepts. We’ll walk through a step-by-step guide to create a sample multiple choice quiz app using HTML, CSS, and JavaScript.

Imagine a website that not only presents information to you but also interacts with you, challenges your knowledge, and provides instant feedback to questions answered. A perfect example of this is a quiz app. You can create dynamic multiple choice quizzes that provide immediate feedback and improve user experience with JavaScript. This app can be educative and entertaining.

JavaScript Concepts for Building a Quiz App

JavaScript is a very powerful library that enables developers to create dynamic websites. It is also a broad language with lots of concepts to learn and master before building simple and complex applications. Here we’ll be using some of these concepts to build our multiple quiz app.

Arrays and Objects

Arrays and objects are useful for organizing data. Here we’ll use them to store questions, choices, and correct answers in structured formats for easy retrieval and manipulation. Take a look at the array method being used in this quiz app:

1
const questions = [
2
  {
3
    question: "What is the capital of United Kingdom?",
4
    choices: ["London", "Paris", "Nairobi"],
5
    correct: 0
6
  },
7
  {
8
    question: "How many days are there in a week?",
9
    choices: ["Five", "Three", "Seven"],
10
    correct: 2
11
  },
12
  {
13
    question: "What is the closest planet to the sun?",
14
    choices: ["Earth", "Mercury", "Saturn"],
15
    correct: 1
16
  },
17
];

In this quiz app, the variable questions is an array that stores the collection of question objects. As you might already know, arrays are enclosed in square brackets [ ]. In this questions array, there are elements within it and each of these elements is an object representing a quiz question. Objects are represented by curly braces { }.

Each of these objects has several properties that relate to each question. The properties are:

  • question: holds a string representing the actual question.
  • choices: holds an array of strings representing the answer choices.
  • correct: holds a number representing the index of the correct answer within the choices array.

So in summary, you’re using an array of objects to represent a collection of quiz questions. Each of these objects contains properties that define the question, answer choices, and the index of the correct answer. This data structure is well-organized, easily accessible, and manageable.

DOM Manipulation

DOM manipulation is a core principle for building interactive web pages and web applications. In the context of this quiz app, you’ll get to use DOM manipulation to dynamically update the content of elements on the page like the question texts and choice buttons. You’ll also use DOM manipulation to display questions, choices, and feedback to users.

1
function showQuestion() {
2
  const questionText = document.getElementById("question-text");
3
  questionText.textContent = questions[currentQuestion].question;
4

5
  const choices = document.querySelectorAll(".choice");
6
  choices.forEach((choice, index) => {
7
    choice.textContent = questions[currentQuestion].choices[index];
8
  });
9

10
  const feedback = document.getElementById("feedback");
11
  feedback.textContent = "";
12
}

So in the above code, we first create a showQuestion function. Then we get a reference to the DOM element we want to manipulate. In this case, it is an element with the ID “question-text”. This has been specified in the HTML file and it is the element where the question text will be displayed.

Next is to update the text content of the “question-text” element using the textContent property. In the code snippet, questionText.textContent is set to the text of the current question obtained from the questions array that is defined at the top of the JavaScript file. This changes the content of the element to display the current question.

The next step is to use the document.querySelectorAll(".choice") to select all elements with the class of “choice”. In the HTML file, the buttons all have the class of “choice”.

After selecting the choice elements, you use a forEach loop to iterate through each choice and update its text content. The text content of each choice is set based on the corresponding choice text in the questions array.

Finally, you clear the previous feedback. You do this by getting a reference to the element with the ID “feedback” (this is a paragraph tag specified in the HTML file) and setting its textContent to an empty string. This will ensure that the feedback message is cleared before displaying new feedback for the current question.

Conditional Statements

When building apps like this, you can’t assume that users will always click on a particular option so you need to create instances for when they select different options. Conditional statements usually have 2 values: true or false. Conditional statements, like if, else if, and switch, are essential for evaluating user input and determining whether answers are correct or incorrect. Feedback and scores will be provided using this logic in the quiz app.

In the code snippet below, you’re using an if statement to check whether the value of “selected” (the user’s chosen answer) is equal to the index of the correct answer stored in questions[currentQuestion].correct. If the condition is true, the code inside the curly braces is executed, indicating that the user’s answer is correct. The feedback text is set to “Correct!” and the correctAnswers counter is incremented by one.

If the condition is false, the code inside the curly braces following the else statement is executed, indicating that the user’s answer is incorrect. The feedback text is set to ”Incorrect!” and the correctAnswers counter isn’t there, so it won’t be incremented.

1
const feedback = document.getElementById("feedback");
2
if (selected === questions[currentQuestion].correct) {
3
  feedback.textContent = "Correct!";
4
  correctAnswers++;
5
} else {
6
  feedback.textContent = "Incorrect!.";
7
}

Are There More Questions?

The second instance where a conditional statement is used in this app is to determine if there are more questions after users answer a question. The code snippet is shown below.

An if statement evaluates whether the current question index (currentQuestion) is less than the total number of questions (questions.length). If the condition currentQuestion < questions.length is true, the code inside the first set of curly braces will execute. Then you call the showQuestion() function to display the next question in the quiz.

If the condition is false, however, the code inside the else block will execute. In this block, you’re accessing the DOM element with the class “quiz-container” (specified in the HTML file) using document.querySelector(".quiz-container"). You then modify the HTML content of this element using the innerHTML property.

1
setTimeout(() => {
2
    currentQuestion++;
3

4
    if (currentQuestion < questions.length) {
5
      showQuestion();
6
    } else {
7
      const quizContainer = document.querySelector(".quiz-container");
8
      quizContainer.innerHTML = `<p>You got ${correctAnswers} out of ${questions.length} questions.</p>`;
9
    }
10
  }, 2000);
11
}

This new content you’re adding to the element is a string that includes the user’s score (correctAnswers) and the total number of questions (questions.length) in the quiz.

Template literals are used to embed expressions directly within a string using the ${...} syntax. This makes your code more readable instead of using the + operator to concatenate strings. In this case, it enables you to easily insert the values of variables(correctAnswers and questions.length) directly into the string without the need for additional syntax.

These conditional statements are all inside a function named “checkAnswer“.

Window setTimeOut Method

The setTimeout function allows us to delay the execution of code. In this app, we use it to introduce a 2-second pause before moving to the next question and to display feedback before the user’s final score is displayed.

1
setTimeout(() => {
2
  // ...
3
}, 2000); // (2000milliseconds = 2 seconds)

Event Handling

This is another core concept that will be used in the creation of this app. With JavaScript, you can build sites that enable you to respond to user interactions, such as clicking buttons, inputting values in a text field, and submitting forms. Event listeners allow you to trigger specific actions when users interact with quiz elements such as question choices.

In this app, we’ll make use of the event handler onClick on the choice buttons to trigger the checkAnswer function when a button is clicked.

1
<button class="choice" onclick="checkAnswer(0)">Paris</button>
2
<button class="choice" onclick="checkAnswer(1)">London</button>
3
<button class="choice" onclick="checkAnswer(2)">Berlin</button>

So we’ve been able to build a simple interactive quiz app using all these JavaScript functions and methods.

Conclusion

Yay! You’ve successfully built an interactive quiz app using HTML, CSS, and JavaScript. By following this tutorial, you’ve gained knowledge on how JavaScript concepts such as DOM manipulation, event handling, conditional statements, and asynchronous behavior like setTimeout can be used to build interactive web applications.

Feel free to further improve this project by customizing the app style, adding more questions, and adding more features. Building an interactive quiz app engages users and lets you apply some JavaScript skills to build dynamic websites, so feel free to experiment around. 

Web Design Myrtle Beach

Coastal Media Brand

© 2024 Coastal Media Brand. All rights Reserved.