Building a Simple Quiz App: Day 72 of 100 Days of Code
Harshil Chovatiya
Introduction
Welcome to Day 72 of the 100 Days of Code challenge! Today, we'll dive into building a simple quiz application using HTML, CSS, and JavaScript. Quizzes are a fun and interactive way to engage users and test their knowledge on various topics. By the end of this tutorial, you'll have a basic understanding of how to create a quiz app from scratch.
Project Overview
In this project, we'll start by designing the layout of our quiz app using HTML and styling it with CSS to make it visually appealing. We'll then use JavaScript to add functionality to our app, including loading questions from an array, displaying them to the user, allowing them to select answers, and providing feedback on their choices.
Here's a brief overview of the key features we'll implement:
- HTML structure for the quiz interface.
- CSS styling for a visually appealing design.
- JavaScript logic to handle quiz functionality:
- Loading questions from an array.
- Displaying questions and multiple-choice answers.
- Handling user input and checking answers.
- Calculating and displaying the final score.
- Allowing users to restart the quiz.
Throughout the project, we'll focus on writing clean and readable code, following best practices, and understanding the concepts behind each step. By the end, you'll have a fully functional quiz app that you can customize and expand further based on your requirements.
Key Features
Let's dive into the key features of our quiz app:
- Interactive User Interface: Engaging layout with clear instructions and options.
- Dynamic Question Loading: Questions loaded from an array for easy management and scalability.
- Immediate Feedback: Users receive instant feedback on their answers.
- Score Tracking: Keep track of users' scores and display them at the end of the quiz.
- Restart Option: Allow users to restart the quiz for another round of fun.
HTML File Overview (index.html)
Start with a simple HTML structure for your Color Pallet Generator:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Quiz App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container" id="start-screen">
<h1>Welcome to the JavaScript Quiz!</h1>
<input type="text" id="username" placeholder="Enter your name">
<button onclick="startQuiz()">Start Quiz</button>
</div>
<div class="container" id="quiz" style="display: none;">
<div id="question-container">
<p id="question"></p>
</div>
<div id="options-container">
</div>
<p id="score">Score: <span id="score-value">0</span></p>
</div>
<div class="container" id="end-screen" style="display: none;">
<h2>Quiz Complete!</h2>
<p>Your score: <span id="final-score">0</span></p>
<button onclick="restartQuiz()">Restart Quiz</button>
</div>
<script src="quiz.js"></script>
</body>
</html>
Styling with CSS:
Here's some basic CSS to style the Color Pallet Generator:
body {
font-family: Arial, sans-serif;
}
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1,
h2 {
text-align: center;
}
input[type="text"] {
width: 100%;
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
display: block;
width: 100%;
padding: 10px;
margin-top: 10px;
border: none;
border-radius: 5px;
background-color: #007bff;
color: #fff;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
#start-screen,
#end-screen {
text-align: center;
margin-top: 50px;
}
#quiz {
max-width: 600px;
margin: 0 auto;
}
.option {
display: block;
width: 100%;
margin-bottom: 10px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
cursor: pointer;
}
.option:hover {
background-color: #f0f0f0;
color: black;
}
#score {
text-align: right;
}
JavaScript:
Now, let's implement the JavaScript to make this application interactive:
const questions = [
{
question: "What is JavaScript?",
options: ["A programming language", "A markup language", "A database language", "A styling language"],
answer: 0
},
{
question: "Which symbol is used for comments in JavaScript?",
options: ["//", "<!--", "/*", "#"],
answer: 0
},
{
question: "What keyword is used to declare variables in JavaScript?",
options: ["dim", "int", "var", "let"],
answer: 2
},
{
question: "Which of the following is NOT a JavaScript data type?",
options: ["string", "boolean", "character", "number"],
answer: 2
},
{
question: "Which function is used to print content in the console?",
options: ["print()", "log()", "display()", "write()"],
answer: 1
},
{
question: "What is the output of '2' + 2 in JavaScript?",
options: ["4", "22", "Error", "NaN"],
answer: 1
},
{
question: "What does the 'this' keyword refer to in JavaScript?",
options: ["The current object", "The parent object", "The global object", "The child object"],
answer: 0
},
{
question: "What is the purpose of the 'use strict' directive in JavaScript?",
options: ["To enable strict mode", "To disable strict mode", "To run JavaScript in strict mode", "To validate code syntax"],
answer: 0
},
{
question: "What is the result of 3 == '3' in JavaScript?",
options: ["true", "false", "Error", "NaN"],
answer: 0
},
{
question: "Which method is used to add a new element to an array in JavaScript?",
options: ["push()", "add()", "append()", "insert()"],
answer: 0
},
{
question: "What does JSON stand for?",
options: ["JavaScript Object Notation", "JavaScript Oriented Notation", "JavaScript Object Naming", "JavaScript Operations Network"],
answer: 0
},
{
question: "What is the result of typeof null in JavaScript?",
options: ["object", "null", "undefined", "number"],
answer: 0
},
{
question: "Which operator is used for strict equality comparison in JavaScript?",
options: ["==", "===", "!=", "!=="],
answer: 1
},
{
question: "What does the Array.isArray() method do in JavaScript?",
options: ["Checks if a value is an array", "Concatenates two arrays", "Reverses an array", "Sorts an array"],
answer: 0
},
{
question: "Which method is used to remove the last element from an array in JavaScript?",
options: ["pop()", "remove()", "delete()", "splice()"],
answer: 0
},
{
question: "What is the result of '20' > '3' in JavaScript?",
options: ["true", "false", "Error", "NaN"],
answer: 0
},
{
question: "Which built-in method returns the length of a string in JavaScript?",
options: ["length()", "size()", "count()", "length"],
answer: 3
},
{
question: "What does the isNaN() function do in JavaScript?",
options: ["Checks if a value is not a number", "Checks if a value is null", "Checks if a value is undefined", "Checks if a value is an object"],
answer: 0
},
{
question: "What is the result of typeof undefined in JavaScript?",
options: ["undefined", "null", "object", "number"],
answer: 0
},
{
question: "Which method is used to join two or more arrays in JavaScript?",
options: ["concat()", "merge()", "join()", "combine()"],
answer: 0
},
{
question: "What is the result of 5 + '5' in JavaScript?",
options: ["10", "55", "Error", "NaN"],
answer: 1
}
];
let currentQuestion = 0;
let score = 0;
function startQuiz() {
const username = document.getElementById('username').value;
if (!username) {
alert("Please enter your name!");
return;
}
document.getElementById('start-screen').style.display = 'none';
document.getElementById('quiz').style.display = 'block';
displayQuestion();
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const shuffledQuestions = shuffle(questions);
function displayQuestion() {
const questionElement = document.getElementById('question');
const optionsContainer = document.getElementById('options-container');
const currentQ = shuffledQuestions[currentQuestion];
questionElement.textContent = currentQ.question;
optionsContainer.innerHTML = "";
currentQ.options.forEach((option, index) => {
const button = document.createElement('button');
button.textContent = option;
button.classList.add('option');
button.onclick = () => checkAnswer(index); // Add onclick event
optionsContainer.appendChild(button);
});
}
function checkAnswer(selectedOption) {
const currentQ = questions[currentQuestion];
const options = document.querySelectorAll('.option');
options.forEach(option => {
option.disabled = true; // Disable all options after selection
});
if (selectedOption === currentQ.answer) {
score++;
}
setTimeout(() => { // Delay before moving to the next question
currentQuestion++;
if (currentQuestion < questions.length) {
displayQuestion();
} else {
showEndScreen();
}
document.getElementById('score-value').textContent = score;
}, 1000); // Adjust delay time if needed
}
function showEndScreen() {
document.getElementById('quiz').style.display = 'none';
document.getElementById('end-screen').style.display = 'block';
document.getElementById('final-score').textContent = score;
}
function restartQuiz() {
currentQuestion = 0;
score = 0;
document.getElementById('end-screen').style.display = 'none';
document.getElementById('start-screen').style.display = 'block';
document.getElementById('username').value = "";
}
Live Example
Here is the Live Preview of the above code
If you're interested in accessing the source code for this todo application, simply click on this link to visit the repository: Click Here. To get a feel for how the application works, you can check out the live preview by clicking here.
Conclusion
Congratulations on completing Day 72 of the 100 Days of Code challenge! You've successfully built a simple quiz app using HTML, CSS, and JavaScript. We covered the process of designing the layout, adding styling to enhance the user experience, and implementing functionality to create an interactive quiz.
This project serves as a solid foundation for further learning and exploration in web development. You can extend the app by adding more questions, implementing features like a timer or a leaderboard, or integrating with external APIs to fetch dynamic content.
Keep practicing, experimenting, and pushing your boundaries as you continue your coding journey. Stay tuned for more exciting projects and challenges ahead!
Comments
Post a Comment