In this lesson, you will learn how to build an interactive quiz application using JavaScript. By the end, you will understand how to manage user inputs and handle events effectively.
An interactive quiz application allows users to answer questions and get immediate feedback. For example, a trivia game where users pick answers and see their scores instantly.
File: quiz.js
const questions = [
{ question: "What is 2 + 2?", options: ["3", "4", "5"], answer: "4" },
{ question: "What is the capital of France?", options: ["Rome", "Paris", "Berlin"], answer: "Paris" }
];
function displayQuiz() {
questions.forEach((q, index) => {
let questionBlock = document.createElement('div');
questionBlock.innerHTML = `<h3>${q.question}</h3>`;
q.options.forEach(option => {
questionBlock.innerHTML += `<button class='option' data-answer='${option}'>${option}</button>`;
});
document.body.appendChild(questionBlock);
});
}
document.addEventListener('DOMContentLoaded', displayQuiz);
document.body.addEventListener('click', e => {
if(e.target.classList.contains('option')) {
const selectedAnswer = e.target.dataset.answer;
const questionIndex = Array.from(e.target.parentElement.parentElement.children).indexOf(e.target.parentElement);
if (selectedAnswer === questions[questionIndex].answer) {
alert('Correct!');
} else {
alert('Wrong answer.');
}
}
});
Expected Output:
When a user clicks on the buttons, they will see either 'Correct!' or 'Wrong answer.'
The function displayQuiz creates the quiz questions and options. The event listener at the end checks the user’s answers and displays alerts based on correctness.
Enhance this quiz application by adding more questions. Create at least three new questions and include different types of responses, like true/false.
const questions = [
{ question: "What is 2 + 2?", options: ["3", "4", "5"], answer: "4" },
{ question: "What is the capital of France?", options: ["Rome", "Paris", "Berlin"], answer: "Paris" },
{ question: "Is the sky blue?", options: ["True", "False"], answer: "True" },
{ question: "Is water wet?", options: ["True", "False"], answer: "True" },
{ question: "Is the sun a star?", options: ["True", "False"], answer: "True" }
];
data-answer to store the correct answer for each option.