Create Quiz App Using Html,Css and JavaScript (Source Code)

Rate this post

Let’s Build Quiz App Using Html, Css, and JavaScript

Hello guys, Welcome to the milgyacode. In today’s blog, we are going to learn how to make a Quiz app website from scratch with just HTML, CSS, and JavaScript. This website has a lot of JavaScript so it will make you good at JavaScript and Dom manipulation. Let’s get right into this. But let’s just watch the video of the quiz app

 

Step-1: Writing the HTML code and add Basic Markup to the Quiz App

Create a new folder and create a file named as index.html in it.

After that start writing the code.

The first code will create a pop-up modal that will be displaying the results of a quiz after the quiz is over. This modal is inside the main element or tag and it will only display when the body of the quiz loads and calls the NextQuestion(0) function. The pop-up is containing a heading that says “Congratulations, Quiz Completed” and also a section that displays the details of the quiz results. These details will tell us the number of attempts and the number of correct and incorrect answers also the percentage of correct answers and a remark. The id attributes are added to some elements inside the pop-up modal content for updating with the real values when once the quiz is over. At the bottom of the pop-up modal, you will also see a button that also has a onclick event that will trigger the closeScoreModal() function which will hide the modal when clicked with the mouse and will allow the user to continue with the quiz or leave the app.

<body onload="NextQuestion(0)">
    <main>
        <!-- creating a modal for when quiz ends -->
        <div class="modal-container" id="score-modal">
         
            <div class="modal-content-container">
             
                <h1>Congratulations, Quiz Completed.</h1>
             
                <div class="grade-details">
                    <p>Attempts : 10</p>
                    <p>Wrong Answers : <span id="wrong-answers"></span></p>
                    <p>Right Answers : <span id="right-answers"></span></p>
                    <p>Grade : <span id="grade-percentage"></span>%</p>
                    <p ><span id="remarks"></span></p>
                </div>
             
                <div class="modal-button-container">
                    <button onclick="closeScoreModal()">Continue</button>
                </div>
             
            </div>
        </div>
    </main>
</body>

After that we will create a new div tag or element just below the previous one which has a class of modal-content-container.

 
 
The container has three main sections inside it which are:
 
Game details container –
This section will contain the information about the game which will include the score of the player out of 10 and also the question number out of 10.
 
Game question container –
This section will display the question which is asked in the quiz at the present time and it’s updated each time when the user click next question button for.
 
Game options container –
This section will display the options to choose as answers to the question asked. Each option has by an radio button and also label. the code also include a modal container that pops up when the user clicks on the “Continue” button inside the game options container (the same pop up modal that we created above a minute ago). This modal will simply ask the user to choose a option before going on to the next question. Once one option is selected the modal is closed and the quiz will go to the next question. At the bottom of the container you will spot that there is a “Next Question” button that will call the handleNextQuestion() function when the “Next Question” button will be clicked to load the next question and also update the game’s details.

 

<div class="game-quiz-container">
          
            <div class="game-details-container">
                <h1>Score : <span id="player-score"></span> / 10</h1>
                <h1> Question : <span id="question-number"></span> / 10</h1>
            </div>

            <div class="game-question-container">
                <h1 id="display-question"></h1>
            </div>

            <div class="game-options-container">
              
               <div class="modal-container" id="option-modal">
                 
                    <div class="modal-content-container">
                         <h1>Please Pick An Option</h1>
                      
                         <div class="modal-button-container">
                            <button onclick="closeOptionModal()">Continue</button>
                        </div>
                      
                    </div>
                 
               </div>
              
                <span>
                    <input type="radio" id="option-one" name="option" class="radio" value="optionA" />
                    <label for="option-one" class="option" id="option-one-label"></label>
                </span>
              

                <span>
                    <input type="radio" id="option-two" name="option" class="radio" value="optionB" />
                    <label for="option-two" class="option" id="option-two-label"></label>
                </span>
              

                <span>
                    <input type="radio" id="option-three" name="option" class="radio" value="optionC" />
                    <label for="option-three" class="option" id="option-three-label"></label>
                </span>
              

                <span>
                    <input type="radio" id="option-four" name="option" class="radio" value="optionD" />
                    <label for="option-four" class="option" id="option-four-label"></label>
                </span>


            </div>

            <div class="next-button-container">
                <button onclick="handleNextQuestion()">Next Question</button>
            </div>

        </div>

Step-2: Writing the CSS code and adding Basic Styling to our Quiz App

Go create a style.css file first

 
lets start coding now
 
* selector is the universal selector and here it is used to 0 margin and padding and telling the box sizing to border box. The html and body elements or tags are given a height of 100vh using the basic height property.
 
The body element will use the ‘Montserrat’ font family and this (body) obviously is the container of our quiz app for all the content. The main element will occupy 100vw width and a minimum height of 100vh using the basic CSS properties called width and min-height properties. The display property is given flex and also the flex-direction to column which will make the main element or tag a flex container with its children elements place vertically.
 
 
The justify-content and align-items properties are set to center to which will make the main place in center both vertically and horizontally. The background property is used to set the background image for the main element or tag, with its URL given in the url() CSS function.
 
The background-repeat and background-size and background-position properties are also given for ensuring that the background img is not repeated and it covers the element and is placed at center. Finally the background-color property is set to black because if the url of the img is not working then the black color will display in place of it.
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
  
html, body{
    height: 100%;
}


body{
    font-family: 'Montserrat', serif;
    
}

main{
    width: 100%;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: black;
    background: url('../assets/background_image.jpg');
    background-color : black;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
}

Next lets add more CSS to under this CSS  

 

This CSS will style the quiz container with its details and questions and options.

.game-quiz-container is for the main container for the quiz. It will give its width with height also background color and display properties and border radius (adds a roundness to corners).

.game-details-container is for the container for the quiz details which also includes the score and the current question number displaying on the screen. It will give its width with height also display and alignment properties.

.game-details-container h1 is for the styling for the headers inside the details container which also gives the font size.

.game-question-container is for the container for the quiz question. It will give its width with height and display also alignment and border properties and adds a border radius too.

.game-question-container h1 is for the styling for the question header which sets its font size also text alignment and padding.

.game-options-container is for the container for the quiz options. It will set its width with height also display properties and alignment.

.game-options-container span is for the styling for each quiz option. It will set their width with height also border and border radius with overflow properties. Each option is located inside a span element.

.game-quiz-container{
    width: 40rem;
    height: 30rem;
    background-color: lightgray;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    border-radius: 30px;
}

.game-details-container{
    width: 80%;
    height: 4rem;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.game-details-container h1{
    font-size: 1.2rem;
}

.game-question-container{
    width: 80%;
    height: 8rem;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px solid darkgray;
    border-radius: 25px;
}

.game-question-container h1{
    font-size: 1.1rem;
    text-align: center;
    padding: 3px;
}

.game-options-container{
    width: 80%;
    height: 12rem;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-around;
}

.game-options-container span{
    width: 45%;
    height: 3rem;
    border: 2px solid darkgray;
    border-radius: 20px;
    overflow: hidden;
}

Next lets now style the options to choose section

This CSS code will selects all label elements inside a span element (option choosing element) and will give their width and height to 100% and also making them fill the entire span container. It also will center the content of the label using flexbox properties. And The cursor property is set to “pointer” so when the person will hover it the cursor will become a pointer.

Restaurant Website Using Html And Css

When a user will hover over a label the code will apply a transform effect to increase its size slightly and creating a visual which will indicate that the label is being hovered over with mouse. The color of the label text will also changed to white. The transition property is used to smoothly animate the transform effect with an duration of 0.3 seconds (0.3s).

span label{
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: transform 0.3s;
    font-weight: 600;
    color: rgb(22, 22, 22);
}

span label:hover{
    -ms-transform: scale(1.12);
    -webkit-transform: scale(1.12);
    transform: scale(1.12);
    color: white;
}

Next lets focus on some more buttons

The first part of the code is the styling for radio buttons. It will give the position to relative and also will hide the display of the radio buttons.

The second part of the code will be responsible for changing the background color of the option container when an radio button will be checked. It uses the (~) to select the option container element that comes after the radio button is checked.

The third part of the code will style the container for the “next” button. It will give the width to 50% and height of 3rem and will align its content to the center.

The next part of the code will style the “next” button. It will give it a width of 8rem and a height of 2rem with border-radius of 10px and background of none alsp font color to rgb(25, 25, 25) and the font weight to 600 and border to 2px solid grey. It also gives the cursor to pointer and removes the outline.

The fifth part of the code will set the hover effect on the “next” button. It will change the background color to rgb(143, 93, 93) when the user will hover over the button with their cursor or mouse.

input[type="radio"] {
    position: relative;
    display: none;
}


input[type=radio]:checked ~ .option {
    background: paleturquoise;
}

.next-button-container{
    width: 50%;
    height: 3rem;
    display: flex;
    justify-content: center;
}
.next-button-container button{
    width: 8rem;
    height: 2rem;
    border-radius: 10px;
    background: none;
    color: rgb(25, 25, 25);
    font-weight: 600;
    border: 2px solid gray;
    cursor: pointer;
    outline: none;
}
.next-button-container button:hover{
    background-color: rgb(143, 93, 93);
}

Lets now style the modal pop up

The .modal-container class will set the starting state of the modal container to be hidden and also positioned to be fixed at the top left corner of the quiz app. It will cover the entire screen with a kind of transparent black background color and will allow scrolling for the content that will exceeds by the screen. The flex properties is centering the container vertically and horizontally on the quiz app, and it will fade-in with a animation effect.

The .modal-content-container class will give the dimensions and background color for the modal’s content container. It will center the content vertically and horizontally with flexbox properties, and will add some more space around its components with the justify-content: space-around flexbox property. It also will apply a border radius of 25 pixels to the container which will add roundness to the container corner. The h1 element inside the container is styled with a font size of 1.3rem with a height of 3rem  and a grey color, and it is centered horizontally and vertically with text-align: center and height: 3rem.

.modal-container{
    display: none;
    position: fixed;
    z-index: 1; 
    left: 0;
    top: 0;
    width: 100%; 
    height: 100%; 
    overflow: auto; 
    background-color: rgb(0,0,0); 
    background-color: rgba(0,0,0,0.4); 
    flex-direction: column;
    align-items: center;
    justify-content: center; 
    -webkit-animation: fadeIn 1.2s ease-in-out;
    animation: fadeIn 1.2s ease-in-out;
}

.modal-content-container{
    height: 20rem;
    width: 25rem;
    background-color: rgb(43, 42, 42);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    border-radius: 25px;
}

.modal-content-container h1{
    font-size: 1.3rem;
    height: 3rem;
    color: lightgray;
    text-align: center;
}

Lets now move to the details section

.grade-details is the container for the details with a width of 15rem and a height of 10rem. It is a flexbox container with a column layout and space-around alignment.

.grade-details p will give the color of the paragraph to white and its placement to center.

.modal-button-container is an container for the button and also a height of 2rem and an width of 100%. It is also a flex box container with default alignment.

.modal-button-container button will set the styling for the button inside the container. It has a width of 10rem with an height of 2rem and font size of 1.1rem. The button has a transparent kind of background with a white border of 1px also white text color and a cursor which is set to pointer. The border-radius property is set to 20px, it will give the button a rounded shape.

.modal-button-container button:hover will give the styling to the button when it will be hovered over by the cursor or mouse and The background color of the button will change to rgb(83, 82, 82).

.grade-details{
    width: 15rem;
    height: 10rem;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
}

.grade-details p{
    color: white;
    text-align: center;
}

.modal-button-container{
    height: 2rem;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.modal-button-container button{
    width: 10rem;
    height: 2rem;
    background: none;
    outline: none;
    border: 1px solid rgb(252, 242, 241);
    color: white;
    font-size: 1.1rem;
    cursor: pointer;
    border-radius: 20px;
}
.modal-button-container button:hover{
    background-color: rgb(83, 82, 82);
}

Let us now set media queries so that are quiz app can be responsive

Media queries are added to this app so that it can be more responsive when we use it in a phone or tablet, media queries are not so difficult to use.

Ecommerce Website Using Html,Css and JavaScript

The first media query will target the screens with a min width of 300px and max width of 350px and will adjust the width and height of the game container and the font sizes of the heading and label. The second media query is for targeting the screens with a min width of 350px and max width of 700px and making similar adjustments to the container and font sizes.

@media(min-width : 300px) and (max-width : 350px){
    .game-quiz-container{
        width: 90%;
        height: 80vh;
     }
     .game-details-container h1{
        font-size: 0.8rem;
     }
 
     .game-question-container{
        height: 6rem;
     }
     .game-question-container h1{
       font-size: 0.9rem;
    }
 
    .game-options-container span{
        width: 90%;
        height: 2.5rem;
    }
    .game-options-container span label{
        font-size: 0.8rem;
    }
    .modal-content-container{
        width: 90%;
        height: 25rem;
    }
    
    .modal-content-container h1{
        font-size: 1.2rem;
    }
}

@media(min-width : 350px) and (max-width : 700px){
   .game-quiz-container{
       width: 90%;
       height: 80vh;
    }
    .game-details-container h1{
        font-size: 1rem;
    }

    .game-question-container{
        height: 8rem;
    }

    .game-question-container h1{
        font-size: 0.9rem;
     }

    .game-options-container span{
        width: 90%;
    }
    .modal-content-container{
        width: 90%;
        height: 25rem;
    }
    .modal-content-container h1{
        font-size: 1.2rem;
    }
}

Lets now complete the CSS with the animation remember i told you that have added a fade in animation before lets now make key frames for that animation.

@keyframes fadeIn and @-webkit-keyframes fadeIn will be defining two separate animations named as “fadeIn” that will be used to fade in the pop up modal gradually. The first one is the standard CSS syntax while the second one is for webkit-based browsers.

The from and to keywords inside the keyframes will define the starting and ending condition of the animation. In this case the opacity of the pop up modal will change from 0 to 1 over time, making it appear to fade in.

@keyframes fadeIn {
    from {opacity: 0;}
    to {opacity:1 ;}
  }

  @-webkit-keyframes fadeIn {
    from {opacity: 0;}
    to {opacity: 1;}
  }

That finished our CSS code.

Step-3: Writing the JavaScript code and adding functionality to our Quiz App

Go create a main.js file.

And Start writing code.

First we are going to create questions for the quiz. lets go.

We’ve created a const variable called questions and inside which we have made some questions with options also the code is very simple its just the matter of syntax here.

const questions = [
    {
        question: "How many days makes a week ?",
        optionA: "10 days",
        optionB: "14 days",
        optionC: "5 days",
        optionD: "7 days",
        correctOption: "optionD"
    },

    {
        question: "How many players are allowed on a soccer pitch ?",
        optionA: "10 players",
        optionB: "11 players",
        optionC: "9 players",
        optionD: "12 players",
        correctOption: "optionB"
    },

    {
        question: "Who was the first President of USA ?",
        optionA: "Donald Trump",
        optionB: "Barack Obama",
        optionC: "Abraham Lincoln",
        optionD: "George Washington",
        correctOption: "optionD"
    },

    {
        question: "30 days has ______ ?",
        optionA: "January",
        optionB: "December",
        optionC: "June",
        optionD: "August",
        correctOption: "optionC"
    },

    {
        question: "How manay hours can be found in a day ?",
        optionA: "30 hours",
        optionB: "38 hours",
        optionC: "48 hours",
        optionD: "24 hours",
        correctOption: "optionD"
    },

    {
        question: "Which is the longest river in the world ?",
        optionA: "River Nile",
        optionB: "Long River",
        optionC: "River Niger",
        optionD: "Lake Chad",
        correctOption: "optionA"
    },

    {
        question: "_____ is the hottest Continent on Earth ?",
        optionA: "Oceania",
        optionB: "Antarctica",
        optionC: "Africa",
        optionD: "North America",
        correctOption: "optionC"
    },

    {
        question: "Which country is the largest in the world ?",
        optionA: "Russia",
        optionB: "Canada",
        optionC: "Africa",
        optionD: "Egypt",
        correctOption: "optionA"
    },

    {
        question: "Which of these numbers is an odd number ?",
        optionA: "Ten",
        optionB: "Twelve",
        optionC: "Eight",
        optionD: "Eleven",
        correctOption: "optionD"
    },

    {
        question: `"You Can't see me" is a popular saying by`,
        optionA: "Eminem",
        optionB: "Bill Gates",
        optionC: "Chris Brown",
        optionD: "John Cena",
        correctOption: "optionD"
    },

    {
        question: "Where is the world tallest building located ?",
        optionA: "Africa",
        optionB: "California",
        optionC: "Dubai",
        optionD: "Italy",
        correctOption: "optionC"
    },

    {
        question: "The longest river in the United Kingdom is ?",
        optionA: "River Severn",
        optionB: "River Mersey",
        optionC: "River Trent",
        optionD: "River Tweed",
        correctOption: "optionA"
    },


    {
        question: "How many permanent teeth does a dog have ?",
        optionA: "38",
        optionB: "42",
        optionC: "40",
        optionD: "36",
        correctOption: "optionB"
    },

    {
        question: "Which national team won the football World cup in 2018 ?",
        optionA: "England",
        optionB: "Brazil",
        optionC: "Germany",
        optionD: "France",
        correctOption: "optionD"
    },

    {
        question: "Which US state was Donald Trump Born ?",
        optionA: "New York",
        optionB: "California",
        optionC: "New Jersey",
        optionD: "Los Angeles",
        correctOption: "optionA"
    },

    {
        question: "How man states does Nigeria have ?",
        optionA: "24",
        optionB: "30",
        optionC: "36",
        optionD: "37",
        correctOption: "optionC"
    },

    {
        question: "____ is the capital of Nigeria ?",
        optionA: "Abuja",
        optionB: "Lagos",
        optionC: "Calabar",
        optionD: "Kano",
        correctOption: "optionA"
    },

    {
        question: "Los Angeles is also known as ?",
        optionA: "Angels City",
        optionB: "Shining city",
        optionC: "City of Angels",
        optionD: "Lost Angels",
        correctOption: "optionC"
    },

    {
        question: "What is the capital of Germany ?",
        optionA: "Georgia",
        optionB: "Missouri",
        optionC: "Oklahoma",
        optionD: "Berlin",
        correctOption: "optionD"
    },

    {
        question: "How many sides does an hexagon have ?",
        optionA: "Six",
        optionB: "Sevene",
        optionC: "Four",
        optionD: "Five",
        correctOption: "optionA"
    },

    {
        question: "How many planets are currently in the solar system ?",
        optionA: "Eleven",
        optionB: "Seven",
        optionC: "Nine",
        optionD: "Eight",
        correctOption: "optionD"
    },

    {
        question: "Which Planet is the hottest ?",
        optionA: "Jupitar",
        optionB: "Mercury",
        optionC: "Earth",
        optionD: "Venus",
        correctOption: "optionB"
    },

    {
        question: "where is the smallest bone in human body located?",
        optionA: "Toes",
        optionB: "Ears",
        optionC: "Fingers",
        optionD: "Nose",
        correctOption: "optionB"
    },

    {
        question: "How many hearts does an Octopus have ?",
        optionA: "One",
        optionB: "Two",
        optionC: "Three",
        optionD: "Four",
        correctOption: "optionC"
    },

    {
        question: "How many teeth does an adult human have ?",
        optionA: "28",
        optionB: "30",
        optionC: "32",
        optionD: "36",
        correctOption: "optionC"
    }

]

Next lets add more JavaScript

This code will define a empty array called shuffledQuestions and also a function called handleQuestions().

The purpose of the function is to shuffle the array of questions and select 10 random questions and those questions will be added to the shuffledQuestions array.

Inside the handleQuestions() function there is a while loop that runs as long as the length of shuffledQuestions is less than or equal to 9.

In each iteration of the while loop a random index will generated using Math.floor(Math.random() * questions.length) where the questions is a array containing all the available questions. The Math.floor function will round down the randomly generated number to the nearest integer.

The if statement checks whether the random question selected already in the shuffledQuestions array or not. If the selected question is not already in the array, it will be added to shuffledQuestions using the push() method.

This process will continue until shuffledQuestions contain 10 unique questions.

let shuffledQuestions = [] //empty array to hold shuffled selected questions

function handleQuestions() { 
    //function to shuffle and push 10 questions to shuffledQuestions array
    while (shuffledQuestions.length <= 9) {
        const random = questions[Math.floor(Math.random() * questions.length)]
        if (!shuffledQuestions.includes(random)) {
            shuffledQuestions.push(random)
        }
    }
}

Lets move ahead 

This code is going declare 4 variables: questionNumber which will represent the current question number and playerScore which will represent the user score and wrongAttempt which will represent the number of wrong attempts made by the user also indexNumber which is the index of the current question in the array of shuffled questions.

The code will also define a function named as NextQuestion which will take a index parameter representing the index of the question to display. The handleQuestions() function will be called inside this function to shuffle and push 10 questions to our shuffledQuestions array.

After that the currentQuestion variable will be set to the question at the specific index in the shuffledQuestions array. The function will update the text content of several HTML elements with the properties of the currentQuestion object. These elements will display the number of the questions with the user score, the question itself along with its four options.

let questionNumber = 1
let playerScore = 0  
let wrongAttempt = 0 
let indexNumber = 0

// function for displaying next question in the array to dom
function NextQuestion(index) {
    handleQuestions()
    const currentQuestion = shuffledQuestions[index]
    document.getElementById("question-number").innerHTML = questionNumber
    document.getElementById("player-score").innerHTML = playerScore
    document.getElementById("display-question").innerHTML = currentQuestion.question;
    document.getElementById("option-one-label").innerHTML = currentQuestion.optionA;
    document.getElementById("option-two-label").innerHTML = currentQuestion.optionB;
    document.getElementById("option-three-label").innerHTML = currentQuestion.optionC;
    document.getElementById("option-four-label").innerHTML = currentQuestion.optionD;

}

Lets now add a function

This code will make a function called checkForAnswer that will be used to check that if the selected answer to the given quiz is correct or not correct.

The function will start by getting the current question and its correct answer, then it will get all the radio inputs with the name “option” from the HTML code and will assign null value to correctOption variable.

It will iterate over each radio input and if that will match the present question’s correct answer, the id of its label element will be assigned to correctOption.

It will then check if none of the radio inputs have been checked. If this is true, it will display an modal with a ID of option-modal.

If a radio input will be checked and it will match the current questions correct answer, it will give the background color to green and will increment the player’s score also will increment the question index number and will set an delay of 1 second before incrementing the number of question.

If a radio input will be checked and if it dont match the current questions answer, then it will give the background color of red and will increment the wrong attempt count and will also increment the question index number and will set an delay of 1 second before incrementing the question number.

function checkForAnswer() {
    const currentQuestion = shuffledQuestions[indexNumber] //gets current Question 
    const currentQuestionAnswer = currentQuestion.correctOption //gets current Question's answer
    const options = document.getElementsByName("option"); //gets all elements in dom with name of 'option' (in this the radio inputs)
    let correctOption = null

    options.forEach((option) => {
        if (option.value === currentQuestionAnswer) {
            //get's correct's radio input with correct answer
            correctOption = option.labels[0].id
        }
    })
   
    //checking to make sure a radio input has been checked or an option being chosen
    if (options[0].checked === false && options[1].checked === false && options[2].checked === false && options[3].checked == false) {
        document.getElementById('option-modal').style.display = "flex"
    }

    //checking if checked radio button is same as answer
    options.forEach((option) => {
        if (option.checked === true && option.value === currentQuestionAnswer) {
            document.getElementById(correctOption).style.backgroundColor = "green"
            playerScore++
            indexNumber++
            //set to delay question number till when next question loads
            setTimeout(() => {
                questionNumber++
            }, 1000)
        }

        else if (option.checked && option.value !== currentQuestionAnswer) {
            const wrongLabelId = option.labels[0].id
            document.getElementById(wrongLabelId).style.backgroundColor = "red"
            document.getElementById(correctOption).style.backgroundColor = "green"
            wrongAttempt++
            indexNumber++
            //set to delay question number till when next question loads
            setTimeout(() => {
                questionNumber++
            }, 1000)
        }
    })
}

Lets now add the functionality of next question

The code below will define two functions called handleNextQuestion() and also resetOptionBackground().

When the user clicks the “Next” button in the game, the handleNextQuestion() function is triggered. As the first step, this function runs the checkForAnswer() function to evaluate whether the user has chosen the right answer for the current question. By doing this, the code ensures that the user receives accurate feedback and moves to the next question only after answering the current question correctly. It then run the unCheckRadioButtons() function to uncheck all radio buttons for the next question. It then waits for 1 second using the setTimeout() function and checks if the current question is the last question. If it is not the last question the it runs the NextQuestion() function to load the next question. If it is the last question, it run the handleEndGame() function to end the game. Finally, it run the resetOptionBackground() function to reset the background color of the options to null.

resetOptionBackground() function resets the background color of all the options to null after displaying the right/wrong colors for the user’s selected answer. It does this by first selecting all the radio buttons with the document.getElementsByName("option") method and then iterating through them using the forEach() method. For each radio button, it selects the label associated with it using the option.labels[0] method and sets its background color to null using the style.backgroundColor = "" method.

//called when the next button is called
function handleNextQuestion() {
    checkForAnswer()
    unCheckRadioButtons()
    //delays next question displaying for a second
    setTimeout(() => {
        if (indexNumber <= 9) {
            NextQuestion(indexNumber)
        }
        else {
            handleEndGame()
        }
        resetOptionBackground()
    }, 1000);
}

//sets options background back to null after display the right/wrong colors
function resetOptionBackground() {
    const options = document.getElementsByName("option");
    options.forEach((option) => {
        document.getElementById(option.labels[0].id).style.backgroundColor = ""
    })
}

Next lets add two more functions

The unCheckRadioButtons() function unchecks all radio buttons on the quiz with the name “option”. It loops through each of the radio buttons and sets its checked property to false.

The handleEndGame() function is called when all questions have been answered. It first determines the player’s remark based on their score, and sets an color for the remark. it calculates the player’s grade percentage and sets that value along with the number of wrong and right answers in the score board. Finally it displays the score board by setting its display style to “flex”.

// unchecking all radio buttons for next question(can be done with map or foreach loop also)
function unCheckRadioButtons() {
    const options = document.getElementsByName("option");
    for (let i = 0; i < options.length; i++) {
        options[i].checked = false;
    }
}

// function for when all questions being answered
function handleEndGame() {
    let remark = null
    let remarkColor = null

    // condition check for player remark and remark color
    if (playerScore <= 3) {
        remark = "Bad Grades, Keep Practicing."
        remarkColor = "red"
    }
    else if (playerScore >= 4 && playerScore < 7) {
        remark = "Average Grades, You can do better."
        remarkColor = "orange"
    }
    else if (playerScore >= 7) {
        remark = "Excellent, Keep the good work going."
        remarkColor = "green"
    }
    const playerGrade = (playerScore / 10) * 100

    //data to display to score board
    document.getElementById('remarks').innerHTML = remark
    document.getElementById('remarks').style.color = remarkColor
    document.getElementById('grade-percentage').innerHTML = playerGrade
    document.getElementById('wrong-answers').innerHTML = wrongAttempt
    document.getElementById('right-answers').innerHTML = playerScore
    document.getElementById('score-modal').style.display = "flex"

}

Without wasting time lets finish the coding with the last functions.

The closeScoreModal() function will be called when the user will click the “close” button on the score modal that appears after all the questions will have been answered. It will reset all necessary variables and calls the NextQuestion() function with a index of 0 to start the game again. Finally it will hide the score modal by setting its display property to “none”.

The closeOptionModal() function will be called when the user will clicks the “close” button on the option modal that appears when the user tries to go to the next question without selecting an answer. It simply hides the option modal by setting its display property to “none”.

//closes score modal and resets game
function closeScoreModal() {
    questionNumber = 1
    playerScore = 0
    wrongAttempt = 0
    indexNumber = 0
    shuffledQuestions = []
    NextQuestion(indexNumber)
    document.getElementById('score-modal').style.display = "none"
}

//function to close warning modal
function closeOptionModal() {
    document.getElementById('option-modal').style.display = "none"
}

That wraps it up.

Let us look at the video again.

Final Output Of Quiz Website:-

 

Live Preview Of Quiz Website:-

 

Is this quiz app responsive, can it run on all devices?

Yes, this quiz app can even work on your mobile phone, tablet, and desktop/laptop.

How is this quiz app made? Using what language?

This is a project which will increase your knowledge of JavaScript this was made with just HTML and CSS and JavaScript.

Does this app even give us a score?

Yes, this quiz app has a feature that will tell you your score at the end of the quiz.

Will it give the same question or it will give questions randomly?

This web app is designed to give you questions randomly with options.

Thanks For Reading this Article!

Leave a Comment