Welcome to Coding Torque, fellow coders! In today’s blog post, we will be embarking on a journey to create a quiz application using the web development technologies of HTML, CSS, and JavaScript. Specifically, we will be using pure JavaScript (also known as “vanilla” JavaScript) to create, display, and check the questions and answers of our quiz. Whether you’re a seasoned developer looking to brush up on your skills or a beginner excited to learn something new, this tutorial has something for everyone. So grab your favorite beverage and let’s get started!
Before we start, here are some JavaScript Games you might like to create:
1.Ā Snake Game using JavaScript
2.Ā 2D Bouncing Ball Game using JavaScript
3.Ā Rock Paper Scissor Game using JavaScript
4.Ā Tic Tac Toe Game using JavaScript
5. Whack a Mole Game using JavaScript
I would recommend you don’t just copy and paste the code, just look at the code and type by understanding it.
HTML CodeĀ
Starter Template
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSS --> <link rel="stylesheet" href="style.css"> <title>Quiz App using JavaScript - @code.scientist x @codingtorque</title> </head> <body> <!-- Further code here --> <script src="script.js"></script> </body> </html>
Paste the below code in your <body>
tag
<div class="start-screen"> <button id="start-button">Start</button> </div> <div id="display-container"> <div class="header"> <div class="number-of-count"> <span class="number-of-question">1 of 3 questions</span> </div> <div class="timer-div"> <img src="https://uxwing.com/wp-content/themes/uxwing/download/time-and-date/stopwatch-icon.png" width="20px" /> <span class="time-left">10s</span> </div> </div> <div id="container"> <!-- questions and options will be displayed here --> </div> <button id="next-button">Next</button> </div> <div class="score-container hide"> <div id="user-score">Demo Score</div> <button id="restart">Restart</button> </div>
Output Till Now
CSS CodeĀ
Create a fileĀ style.css
and paste the code below.
* { padding: 0; margin: 0; box-sizing: border-box; font-family: "Poppins", sans-serif; } body { height: 100vh; background: linear-gradient(184deg,#8754ff,#8E2DE2); } .start-screen, .score-container { position: absolute; top: 0; width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; } button { border: none; outline: none; cursor: pointer; } #start-button, #restart { font-size: 1.3em; padding: 0.5em 1.8em; border-radius: 0.2em; box-shadow: 0 20px 30px rgba(0, 0, 0, 0.4); } #restart { margin-top: 0.9em; } #display-container { background-color: #ffffff; padding: 3.1em 1.8em; width: 80%; max-width: 37.5em; margin: 0 auto; position: absolute; transform: translate(-50%, -50%); top: 50%; left: 50%; border-radius: 0.6em; } .header { margin-bottom: 1.8em; display: flex; justify-content: space-between; align-items: center; padding-bottom: 0.6em; border-bottom: 0.1em solid #c0bfd2; } .timer-div { background-color: #e1f5fe; width: 7.5em; border-radius: 1.8em; display: flex; align-items: center; justify-content: space-between; padding: 0.7em 1.8em; } .question { margin-bottom: 1.25em; font-weight: 600; } .option-div { font-size: 0.9em; width: 100%; padding: 1em; margin: 0.3em 0; text-align: left; outline: none; background: transparent; border: 1px solid #c0bfd2; border-radius: 0.3em; } .option-div:disabled { color: #000000; cursor: not-allowed; } #next-button { font-size: 1em; margin-top: 1.5em; background-color: #8754ff; color: #ffffff; padding: 0.7em 1.8em; border-radius: 0.3em; float: right; box-shadow: 0px 20px 40px rgba(0, 0, 0, 0.3); } .hide { display: none; } .incorrect { background-color: #ffdde0; color: #d32f2f; border-color: #d32f2f; } .correct { background-color: #e7f6d5; color: #689f38; border-color: #689f38; } #user-score { font-size: 1.5em; color: #ffffff; }
Output Till Now
JavaScript CodeĀ
script.js
Ā and paste the code below.//References let timeLeft = document.querySelector(".time-left"); let quizContainer = document.getElementById("container"); let nextBtn = document.getElementById("next-button"); let countOfQuestion = document.querySelector(".number-of-question"); let displayContainer = document.getElementById("display-container"); let scoreContainer = document.querySelector(".score-container"); let restart = document.getElementById("restart"); let userScore = document.getElementById("user-score"); let startScreen = document.querySelector(".start-screen"); let startButton = document.getElementById("start-button"); let questionCount; let scoreCount = 0; let count = 11; let countdown; //Questions and Options array const quizArray = [ { id: "0", question: "Which is the most widely spoken language in the world?", options: ["Spanish", "Mandarin", "English", "German"], correct: "Mandarin", }, { id: "1", question: "Which is the only continent in the world without a desert?", options: ["North America", "Asia", "Africa", "Europe"], correct: "Europe", }, { id: "2", question: "Who invented Computer?", options: ["Charles Babbage", "Henry Luce", "Henry Babbage", "Charles Luce"], correct: "Charles Babbage", }, { id: "3", question: "What do you call a computer on a network that requests files from another computer?", options: ["A client", "A host", "A router", "A web server"], correct: "A client", }, { id: "4", question: "Hardware devices that are not part of the main computer system and are often added later to the system.", options: ["Peripheral", "Clip art", "Highlight", "Execute"], correct: "Peripheral", }, { id: "5", question: "The main computer that stores the files that can be sent to computers that are networked together is:", options: ["Clip art", "Mother board", "Peripheral", "File server"], correct: "File server", }, { id: "6", question: "How can you catch a computer virus?", options: ["Sending e-mail messages", "Using a laptop during the winter", "Opening e-mail attachments", "Shopping on-line"], correct: "Opening e-mail attachments", }, { id: "7", question: "Google (www.google.com) is a:", options: ["Search Engine", "Number in Math", "Directory of images", "Chat service on the web"], correct: "Search Engine", }, { id: "8", question: "Which is not an Internet protocol?", options: ["HTTP", "FTP", "STP", "IP"], correct: "STP", }, { id: "9", question: "Which of the following is not a valid domain name?", options: ["www.yahoo.com", "www.yahoo.co.uk", "www.com.yahoo", "www.yahoo.co.in"], correct: "www.com.yahoo", }, ]; //Restart Quiz restart.addEventListener("click", () => { initial(); displayContainer.classList.remove("hide"); scoreContainer.classList.add("hide"); }); //Next Button nextBtn.addEventListener( "click", (displayNext = () => { //increment questionCount questionCount += 1; //if last question if (questionCount == quizArray.length) { //hide question container and display score displayContainer.classList.add("hide"); scoreContainer.classList.remove("hide"); //user score userScore.innerHTML = "Your score is " + scoreCount + " out of " + questionCount; } else { //display questionCount countOfQuestion.innerHTML = questionCount + 1 + " of " + quizArray.length + " Question"; //display quiz quizDisplay(questionCount); count = 11; clearInterval(countdown); timerDisplay(); } }) ); //Timer const timerDisplay = () => { countdown = setInterval(() => { count--; timeLeft.innerHTML = `${count}s`; if (count == 0) { clearInterval(countdown); displayNext(); } }, 1000); }; //Display quiz const quizDisplay = (questionCount) => { let quizCards = document.querySelectorAll(".container-mid"); //Hide other cards quizCards.forEach((card) => { card.classList.add("hide"); }); //display current question card quizCards[questionCount].classList.remove("hide"); }; //Quiz Creation function quizCreator() { //randomly sort questions quizArray.sort(() => Math.random() - 0.5); //generate quiz for (let i of quizArray) { //randomly sort options i.options.sort(() => Math.random() - 0.5); //quiz card creation let div = document.createElement("div"); div.classList.add("container-mid", "hide"); //question number countOfQuestion.innerHTML = 1 + " of " + quizArray.length + " Question"; //question let question_DIV = document.createElement("p"); question_DIV.classList.add("question"); question_DIV.innerHTML = i.question; div.appendChild(question_DIV); //options div.innerHTML += ` <button class="option-div" onclick="checker(this)">${i.options[0]}</button> <button class="option-div" onclick="checker(this)">${i.options[1]}</button> <button class="option-div" onclick="checker(this)">${i.options[2]}</button> <button class="option-div" onclick="checker(this)">${i.options[3]}</button> `; quizContainer.appendChild(div); } } //Checker Function to check if option is correct or not function checker(userOption) { let userSolution = userOption.innerText; let question = document.getElementsByClassName("container-mid")[questionCount]; let options = question.querySelectorAll(".option-div"); //if user clicked answer == correct option stored in object if (userSolution === quizArray[questionCount].correct) { userOption.classList.add("correct"); scoreCount++; } else { userOption.classList.add("incorrect"); //For marking the correct option options.forEach((element) => { if (element.innerText == quizArray[questionCount].correct) { element.classList.add("correct"); } }); } //clear interval(stop timer) clearInterval(countdown); //disable all options options.forEach((element) => { element.disabled = true; }); } //initial setup function initial() { quizContainer.innerHTML = ""; questionCount = 0; scoreCount = 0; count = 11; clearInterval(countdown); timerDisplay(); quizCreator(); quizDisplay(questionCount); } //when user click on start button startButton.addEventListener("click", () => { startScreen.classList.add("hide"); displayContainer.classList.remove("hide"); initial(); }); //hide quiz and display start screen window.onload = () => { startScreen.classList.remove("hide"); displayContainer.classList.add("hide"); };