Code-Along: Personal Quiz
Follow this guide to create and customize an interactive quiz. These instructions use Ash Ketchum as an example subject, but make sure to change the questions and answers to be about you!
Part 1 - Setup
Start by copying the existing project. It contains all of the HTML and CSS, but none of the JavaScript.
Click here to copy the project!
Open the preview to see how it looks. Everything should show up on the page, but the button will not be functional yet...
Part 2 - Hooking Up the Button
There is currently no JavaScript code, so nothing happens when the button is clicked! Take a look at the <button> element in the HTML:
<button onclick="startQuiz()">Start the Quiz</button>
The onclick attribute is trying to call a function named startQuiz - you have to define it!
- Open the script.js file for editing
- At the top, define a function named
startQuizfunctionkeyword- Function name (
startQuiz) - Parentheses (
()) - Curly brackets (
{})
- Make a new line in the body of the function
- Between the curly brackets
- There, add an
alertstatement that says "Loading..." - Run the project again, click the button, and verify that a pop-up appears!
The code in the script.js file should look something like this:
function startQuiz() {
alert("Loading...");
}
Part 3 - Adding a Personal Greeting
The button is working, but it's not doing anything too exciting yet. Welcome the user to the quiz with a personalized message using the name they entered in the text input!
- Make a new line in the body of the
startQuizfunction - There, create a new variable named
nameInput - Set the
nameInputvalue to get the<input id="name">element from the HTML- Use
document.querySelectorto accomplish this
- Use
- Under that, create a new variable named
name - Set the
namevalue to get the actual text from thenameInputelement- Use
.valueto accomplish this
- Use
- Under that, add an
alertthat says "Hello, NAME! Get ready for some questions..." - Make the message into a template string, and replace "NAME" with
${name}to use the text from the box - Run the project again, enter a name in the text box, click the button, and verify that the greeting is personalized!
The additional code within the body of the startQuiz function should look something like this:
let nameInput = document.querySelector("#name");
let name = nameInput.value;
alert(`Hello, ${name}! Get ready for some questions...`);
Part 4 - Preparing the Score
Now it's time to get into the quiz! Start by setting up some storage variables to keep track of the player's score.
- Make a new line in the body of the
startQuizfunction - There, create a new variable named
score - Set the
scorevalue to0to start - Under that, create a new variable named
numQuestions - Set the
numQuestionsvalue to3.0for now- The
.0is for calculation purposes
- The
Note that nothing will actually change when clicking the button again - these variables will be used a bit later. The additional code within the body of the startQuiz function should look something like this:
let score = 0;
let numQuestions = 3.0;
Part 5 - Asking One Question
Now that the variables are initialized, this quiz needs some questions! Start with this one:
| Question | Answer |
|---|---|
| What is my name? | Ash Ketchum |
- Make a new line at the bottom of the
startQuizfunction - There, create a variable named
answer1 - Set
answer1to the result of apromptasking "What is my name?" - Under that, create an
ifstatementifkeyword- Parentheses (
()) - Curly brackets (
{})
- For the condition (between parentheses), check if
answer1is equal to"Ash Ketchum"- Use
===to compare the two
- Use
- In the body of the
if(between curly brackets), make a new line - There, set
scoreto bescore + 1- This increases the score by 1!
- Click the button, and verify that the new prompt appears!
The additional code within the body of the startQuiz function should look something like this:
let answer1 = prompt("What is my name?");
if (answer1 === "Ash Ketchum") {
score = score + 1;
}
Part 6 - Asking More Questions
Additional questions will use almost exactly the same code as the first question. The only things that will change are:
- The answer variable name (e.g.,
answer2instead ofanswer1) - The question text (e.g.,
"Where do I live?"instead of"What is my name?")
Other than that, you can follow the steps from Part 5 to add each additional question! Add at least two more:
| Question | Answer |
|---|---|
| Where do I live? | Kanto |
| What is my cat's name? | Pikachu |
Note: If there are more or less than three questions, the value of the
numQuestionsvariable will need to change
The code for the additional questions should look something like this:
let answer2 = prompt("Where do I live?");
if (answer2 === "Kanto") {
score = score + 1;
}
let answer3 = prompt("What is my cat's name?");
if (answer3 === "Pikachu") {
score = score + 1;
}
Now the quiz is complete, but the player has no idea if they got the questions right or wrong!
Part 7 - Calculating and Displaying the Result
At this point, the startQuiz function knows the number of correct answers (stored in the score variable), so the final result can be calculated. There will be a little math involved, and then the player will get a nice message saying whether they passed or failed.
- Make a new line at the bottom of the
startQuizfunction - There, add an
alertthat says "Calculating..." - Under that, create a variable named
scorePercent - Set the
scorePercentvariable to be100timesscoredivided bynumQuestions- This is their final percentage based on how many they got right
- Under that, create an
if/elsestructureifkeyword- Parentheses
- Curly brackets
elsekeyword- More curly brackets
- For the condition (between parentheses), check if
scorePercentis greater than60 - In the body of the
if, use analertto say "You passed 😎" - In the body of the
else, use analertto say "You failed 😭" - Run the project, take the quiz, and make sure the calculation is correct!
The additional code within the body of the startQuiz function should look something like this:
alert("Calculating...");
let scorePercent = 100 * (score / numQuestions);
if (scorePercent > 60) {
alert("You passed 😎");
} else {
alert("You failed 😭");
}
Part 8 - Revealing the Final Score
A simple "pass" or "fail" is nice, but the player might want to know their exact score. There is actually already a <p> element in the HTML just for this purpose! Its text can update dynamically based on the quiz result.
- Make a new line at the bottom of the
startQuizfunction - There, create a new variable named
scoreElement - Set the
scoreElementvalue to get the<p id="score">element from the HTML- Use
document.querySelectorto accomplish this
- Use
- Set the text of the
<p>to a message saying "You got SCORE correct (PERCENT%)"- Use
.textContentto accomplish this
- Use
- Make the message into a template string, and replace "SCORE" and "PERCENT" with
${score}and${scorePercent}- This will use the actual score and percentage values
- Run the project, take the quiz again, and verify that the correct score appears on the page after it!
The added code should look something like this:
let scoreElement = document.querySelector("#score");
scoreElement.textContent = `You got ${score} correct (${scorePercent}%)`;
Part 9 - Presenting the Stars
The quiz is functionally complete now, but the player might want a bit more of a prize for their efforts. Add some star images to the page based on how many questions the player got right!
- Make a new line at the bottom of the
startQuizfunction - There, create a
forloop structureforkeyword- Parentheses (
()) - Curly brackets (
{})
- Add statements within the parentheses to repeat a number of times
let i = 0;i < NUMBER;i++
- Make the loop repeat
scoretimes instead ofNUMBERtimes- This way, the code in the loop will run once for every correct answer
- Make a new line in the body of the loop (between curly brackets)
- There, create a new variable named
starImg - Set
starImgto be a newly created<img>element- Use
document.createElementto accomplish this
- Use
- Under that, set the
srcofstarImgto be"https://github.com/hytechclub/web-103/blob/main/Assets/star.png?raw=true"- The star.png file should be accessible through the URL
- Under that, append the
starImgelement to thebodyof the page- Use
document.body.appendChildto accomplish this
- Use
- Run the project, take the quiz again, and see how many stars you see!
The added code should look something like this:
for (let i = 0; i < score; i++) {
let starImg = document.createElement("img");
starImg.src = "https://github.com/hytechclub/web-103/blob/main/Assets/star.png?raw=true";
document.body.appendChild(starImg);
}
Conclusion
And that's it! The quiz should be fully functional and fully fun. The code in the script.js file should look something like this at the end:
function startQuiz() {
alert("Loading...");
let nameInput = document.querySelector("#name");
let name = nameInput.value;
alert(`Hello, ${name}! Get ready for some questions...`);
let score = 0;
let numQuestions = 3.0;
let answer1 = prompt("What is my name?");
if (answer1 === "Ash Ketchum") {
score = score + 1;
}
let answer2 = prompt("Where do I live?");
if (answer2 === "Kanto") {
score = score + 1;
}
let answer3 = prompt("What is my cat's name?");
if (answer3 === "Pikachu") {
score = score + 1;
}
alert("Calculating...");
let scorePercent = 100 * (score / numQuestions);
if (scorePercent > 60) {
alert("You passed 😎");
} else {
alert("You failed 😭");
}
let scoreElement = document.querySelector("#score");
scoreElement.textContent = `You got ${score} correct (${scorePercent}%)`;
for (let i = 0; i < score; i++) {
let starImg = document.createElement("img");
starImg.src = "https://github.com/hytechclub/web-103/blob/main/Assets/star.png?raw=true";
document.body.appendChild(starImg);
}
}