• About Us
  • Privacy Policy
  • Disclaimer
  • Contact Us
AimactGrow
  • Home
  • Technology
  • AI
  • SEO
  • Coding
  • Gaming
  • Cybersecurity
  • Digital marketing
No Result
View All Result
  • Home
  • Technology
  • AI
  • SEO
  • Coding
  • Gaming
  • Cybersecurity
  • Digital marketing
No Result
View All Result
AimactGrow
No Result
View All Result

How one can Make a Easy JavaScript Quiz: Code Tutorial — SitePoint

Admin by Admin
July 5, 2025
Home Coding
Share on FacebookShare on Twitter


to show the outcomes.

Right here’s how that will look:

<div id="quiz">div>
<button id="submit">Submit Quizbutton>
<div id="outcomes">div>

This construction is an easy instance of learn how to create quiz HTML code that serves as a basis in your JavaScript quiz template. When you run the applying now, you’ll simply see a “Submit Quiz” button.

Step 2 – Initialize JavaScript Variables

Now, we are able to use the JavaScript doc.getElementById methodology to pick the above HTML parts and retailer references to them within the JavaScript quiz code like under:

const quizContainer = doc.getElementById('quiz');
const resultsContainer = doc.getElementById('outcomes');
const submitButton = doc.getElementById('submit');

The following factor our quiz app wants is a few inquiries to show. We’ll use JavaScript object literals to signify the person questions and an array to carry the entire questions that make up our quiz app. Utilizing an array will make the questions simple to iterate over:

const myQuestions = [
  {
    question: "Who invented JavaScript?",
    answers: {
      a: "Douglas Crockford",
      b: "Sheryl Sandberg",
      c: "Brendan Eich"
    },
    correctAnswer: "c"
  },
  {
    question: "Which one of these is a JavaScript package manager?",
    answers: {
      a: "Node.js",
      b: "TypeScript",
      c: "npm"
    },
    correctAnswer: "c"
  },
  {
    question: "Which tool can you use to ensure code quality?",
    answers: {
      a: "Angular",
      b: "jQuery",
      c: "RequireJS",
      d: "ESLint"
    },
    correctAnswer: "d"
  }
];

Be at liberty to place in as many questions or solutions as you need.

Notice: As that is an array, the questions will seem within the order they’re listed. If you wish to kind the questions in any manner earlier than presenting them to the person, take a look at our fast tip on sorting an array of objects in JavaScript.

Step 3 – Construct the Quiz Perform

Now that we have now our record of questions, we are able to present them on the web page. For that, we can be utilizing a perform named buildQuix(). Let’s undergo the next JavaScript line by line to see the way it works:

First, we create an output variable to include all of the HTML output, together with questions and reply decisions.

Subsequent, we are able to begin constructing the HTML for every query. We’ll have to loop by way of every query like this:

myQuestions.forEach( (currentQuestion, questionNumber) => {
  
});

For brevity, we’re utilizing an arrow perform to carry out our operations on every query. As a result of that is in a forEach loop, we get the present worth, the index (the place quantity of the present merchandise within the array), and the array itself as parameters. We solely want the present worth and the index, which for our functions, we’ll title currentQuestion and questionNumber respectively.

Now let’s have a look at the code inside our loop:

For every query, we’ll wish to generate the right HTML. So, our first step is to create an array to carry the record of doable solutions.s.

Subsequent, we’ll use a loop to fill within the doable solutions for the present query. For every alternative, we’re creating an HTML radio button, which we enclose in a

Right here, we’re utilizing template literals, that are strings however extra highly effective. We’ll make use of the next options of template literals:

  • Multi-line capabilities.
  • Don’t want to make use of escape quotes inside quotes as a result of template literals use backticks.
  • String interpolation permits embedding JavaScript expressions proper into your strings like this: ${code_goes_here}.

As soon as we have now our record of reply buttons, we are able to push the query HTML and the reply HTML onto our general record of outputs.

Discover that we’re utilizing a template literal and a few embedded expressions to first create the query div after which create the reply div. The be a part of expression takes our record of solutions and places them collectively in a single string that we are able to output into our solutions div.

Now that we’ve generated the HTML for every query, we are able to be a part of all of it collectively and present it on the web page:

quizContainer.innerHTML = output.be a part of('');

Now, our buildQuiz perform is full, and it’s best to be capable of run the quiz app and see the questions displayed.

Nonetheless, the construction of your code is necessary. As a consequence of one thing referred to as the temporal lifeless zone, you’ll be able to’t reference your query array earlier than it has been outlined.

To recap, that is the right construction:


perform buildQuiz(){ ... }
perform showResults(){ ... }


const quizContainer = doc.getElementById('quiz');
const resultsContainer = doc.getElementById('outcomes');
const submitButton = doc.getElementById('submit');
const myQuestions = [ ... ];


buildQuiz();


submitButton.addEventListener('click on', showResults);

Step 4 – Displaying the Quiz Outcomes

At this level, we wish to construct out our showResults perform to loop over the solutions, examine them, and present the outcomes. This can be a essential a part of any quiz sport JavaScript implementation, because it supplies instant suggestions to the person primarily based on their efficiency.

Right here’s the perform, which we’ll undergo intimately subsequent:

perform showResults(){

  
  const answerContainers = quizContainer.querySelectorAll('.solutions');

  
  let numCorrect = 0;

  
  myQuestions.forEach( (currentQuestion, questionNumber) => {

    
    const answerContainer = answerContainers[questionNumber];
    const selector = `enter[name=question${questionNumber}]:checked`;
    const userAnswer = (answerContainer.querySelector(selector) || {}).worth;

    
    if(userAnswer === currentQuestion.correctAnswer){
      
      numCorrect++;

      
      answerContainers[questionNumber].fashion.colour = 'lightgreen';
    }
    
    else{
      
      answerContainers[questionNumber].fashion.colour = 'pink';
    }
  });

  
  resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.size}`;
}

First, we choose all the reply containers in our quiz’s HTML. Then, we’ll create variables to maintain monitor of the person’s present reply and the overall variety of right solutions.


const answerContainers = quizContainer.querySelectorAll('.solutions');


let numCorrect = 0;

Now, we are able to loop by way of every query and examine the solutions.

We can be utilizing 3 steps for that:

  • Discover the chosen reply within the HTML.
  • Deal with what occurs if the reply is right.
  • Deal with what occurs if the reply is fallacious.

Let’s look extra carefully at how we’re discovering the chosen reply in our HTML:


const answerContainer = answerContainers[questionNumber];
const selector = `enter[name=question${questionNumber}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) || {}).worth;

First, we’re ensuring we’re trying inside the reply container for the present query.

Within the subsequent line, we’re defining a CSS selector that can allow us to discover which radio button is checked.

Then we’re utilizing JavaScript’s querySelector to seek for our CSS selector within the beforehand outlined answerContainer. In essence, because of this we’ll discover which reply’s radio button is checked.

Lastly, we are able to get the worth of that reply through the use of .worth.

Coping with Incomplete Consumer Enter

What if the person has left a solution clean? On this case, utilizing .worth would trigger an error as a result of you’ll be able to’t get the worth of one thing that’s not there. To resolve this, we’ve added ||, which implies “or”, and {}, which is an empty object. Now, the general assertion says:

  • Get a reference to our chosen reply aspect OR, if that doesn’t exist, use an empty object.
  • Get the worth of no matter was within the first assertion.

Because of this, the worth will both be the person’s reply or undefined, which implies a person can skip a query with out crashing our quiz app.

Evaluating the Solutions and Displaying the End result

The following statements in our answer-checking loop will allow us to deal with right and incorrect solutions.


if(userAnswer === currentQuestion.correctAnswer){
  
  numCorrect++;

  
  answerContainers[questionNumber].fashion.colour = 'lightgreen';
}

else{
  
  answerContainers[questionNumber].fashion.colour = 'pink';
}

If the person’s reply matches the right alternative, enhance the variety of right solutions by one and (optionally) colour the set of decisions inexperienced. If the reply is fallacious or clean, colour the reply decisions pink (once more, optionally available).

As soon as the answer-checking loop is completed, we are able to present what number of questions the person obtained proper:


resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.size}`;

And now we have now a working JavaScript quiz!

When you’d like, you’ll be able to wrap the entire quiz in an IIFE (instantly invoked perform expression), which is a perform that runs as quickly as you outline it. This can preserve your variables out of world scope and be certain that your quiz app doesn’t intervene with every other scripts operating on the web page.

Now you’re all set! Be at liberty so as to add or take away questions and solutions and magnificence the quiz nevertheless you want.

Now, if you happen to run the applying, you’ll be able to choose the solutions and submit the quiz to get the outcomes.

Step 5 – Including Types

Since now we have now a working quiz, let’s make it extra person pleasant by including some kinds. Nonetheless, I received’t be going into particulars of every fashion. You may instantly copy the under code into the kinds.css file.

 @import url(https://fonts.googleapis.com/css?household=Work+Sans:300,600);

physique{
  font-size: 20px;
  font-family: 'Work Sans', sans-serif;
  colour: #333;
  font-weight: 300;
  text-align: heart;
  background-color: #f8f6f0;
}
h1{
  font-weight: 300;
  margin: 0px;
  padding: 10px;
  font-size: 20px;
  background-color: #444;
  colour: #fff;
}
.query{
  font-size: 30px;
  margin-bottom: 10px;
}
.solutions {
  margin-bottom: 20px;
  text-align: left;
  show: inline-block;
}
.solutions label{
  show: block;
  margin-bottom: 10px;
}
button{
  font-family: 'Work Sans', sans-serif;
  font-size: 22px;
  background-color: #279;
  colour: #fff;
  border: 0px;
  border-radius: 3px;
  padding: 20px;
  cursor: pointer;
  margin-bottom: 20px;
}

button:hover{
  background-color: #38a;
}

.slide{
  place: absolute;
  left: 0px;
  prime: 0px;
  width: 100%;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.5s;
}
.active-slide{
  opacity: 1;
  z-index: 2;
}
.quiz-container{
  place: relative;
  top: 200px;
  margin-top: 40px;
}

At this level, your quiz may seem like this (with a tiny little bit of styling):

As you’ll be able to see within the above photographs, the questions within the quiz are ordered one after one other. We now have to scroll down to pick our solutions. Though this seems fantastic with three questions, you may begin struggling to reply them when the variety of questions will increase. So, we have to discover a technique to present just one query at a time by way of pagination.

For that, you’ll want:

  • A technique to present and conceal questions.
  • Buttons to navigate the quiz.

So, let’s make some changes to our code, beginning with HTML:

<div class="quiz-container">
  <div id="quiz">div>
div>
<button id="earlier">Earlier Querybutton>
<button id="subsequent">Subsequent Querybutton>
<button id="submit">Submit Quizbutton>
<div id="outcomes">div>

Most of that markup is similar as earlier than, however now we’ve added navigation buttons and a quiz container. The quiz container will assist us place the questions as layers that we are able to present and conceal.

Subsequent, contained in the buildQuiz perform, we have to add a

aspect with class slide to carry the query and reply containers that we simply created:

output.push(
  `<div class="slide">
    <div class="query"> ${currentQuestion.query} div>
    <div class="solutions"> ${solutions.be a part of("")} div>
  div>`
);

Subsequent, we are able to use some CSS positioning to make the slides sit as layers on prime of each other. On this instance, you’ll discover we’re utilizing z-indexes and opacity transitions to permit our slides to fade out and in. Right here’s what that CSS may seem like:

.slide{
  place: absolute;
  left: 0px;
  prime: 0px;
  width: 100%;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.5s;
}
.active-slide{
  opacity: 1;
  z-index: 2;
}
.quiz-container{
  place: relative;
  top: 200px;
  margin-top: 40px;
}

Now we’ll add some JavaScript to make the pagination work. As earlier than, the order is necessary, so that is the revised construction of our code:








buildQuiz();





showSlide(currentSlide);



We will begin with some variables to retailer references to our navigation buttons and preserve monitor of which slide we’re on. Add these after the decision to buildQuiz(), as proven above:


const previousButton = doc.getElementById("earlier");
const nextButton = doc.getElementById("subsequent");
const slides = doc.querySelectorAll(".slide");
let currentSlide = 0;

Subsequent we’ll write a perform to indicate a slide. Add this beneath the prevailing capabilities (buildQuiz and showResults):

perform showSlide(n) {
  slides[currentSlide].classList.take away('active-slide');
  slides[n].classList.add('active-slide');
  currentSlide = n;
  if(currentSlide === 0){
    previousButton.fashion.show = 'none';
  }
  else{
    previousButton.fashion.show = 'inline-block';
  }
  if(currentSlide === slides.size-1){
    nextButton.fashion.show = 'none';
    submitButton.fashion.show = 'inline-block';
  }
  else{
    nextButton.fashion.show = 'inline-block';
    submitButton.fashion.show = 'none';
  }
}

Right here’s what the primary three strains do:

  • Disguise the present slide by eradicating the active-slide class.
  • Present the brand new slide by including the active-slide class.
  • Replace the present slide quantity.

The following strains introduce the next JavaScript logic:

  • If we’re on the primary slide, disguise the Earlier Slide button. In any other case, present the button.
  • If we’re on the final slide, disguise the Subsequent Slide button and present the Submit button. In any other case, present the Subsequent Slide button and conceal the Submit button.

After we’ve written our perform, we are able to instantly name showSlide(0) to indicate the primary slide. This could come after the pagination code:


...

showSlide(currentSlide);

Subsequent we are able to write capabilities to make the navigation buttons work. These go beneath the showSlide perform:

perform showNextSlide() {
  showSlide(currentSlide + 1);
}

perform showPreviousSlide() {
  showSlide(currentSlide - 1);
}

Right here, we’re making use of our showSlide perform to permit our navigation buttons to indicate the earlier slide and the subsequent slide.

Lastly, we’ll have to hook the navigation buttons as much as these capabilities. This comes on the finish of the code:


...
previousButton.addEventListener("click on", showPreviousSlide);
nextButton.addEventListener("click on", showNextSlide);

Now your quiz has working navigation!

What’s Subsequent?

Now that you’ve a primary JavaScript quiz app, it’s time to get artistic and experiment.

Listed here are some solutions you’ll be able to attempt:

  • Attempt other ways of responding to an accurate reply or a fallacious reply.
  • Type the quiz properly.
  • Add a progress bar.
  • Let customers evaluation solutions earlier than submitting.
  • Give customers a abstract of their solutions after they submit them.
  • Replace the navigation to let customers skip to any query quantity.
  • Create customized messages for every stage of outcomes. For instance, if somebody scores 8/10 or greater, name them a quiz ninja.
  • Add a button to share outcomes on social media.
  • Save your excessive scores utilizing localStorage.
  • Add a countdown timer to see if folks can beat the clock.
  • Apply the ideas from this text to different makes use of, akin to a mission value estimator, or a social “which-character-are-you” quiz.

FAQs on How one can Make a Easy JavaScript Quiz

How Can I Add Extra Inquiries to the JavaScript Quiz?

Including extra inquiries to your JavaScript quiz is an easy course of. That you must add extra objects to the questions array in your JavaScript code. Every object represents a query and has two properties: textual content (the query itself) and responses (an array of doable solutions). Right here’s an instance of how one can add a brand new query:

questions.push({ 
  textual content: 'What's the capital of France?', 
  responses: [ 
  { 
    text: 'Paris', 
    correct: true 
  }, 
  { 
    text: 'London', 
    correct: false 
  }, 
  {
    text: 'Berlin', 
    correct: false 
  }, 
  { 
    text: 'Madrid', 
    correct: false 
  } 
  ] 
});

On this instance, we’re including a query in regards to the capital of France, with 4 doable solutions. The right reply is marked with ‘right: true’.

How Can I Randomize the Order of Questions within the Quiz?

Randomizing the order of questions could make your quiz more difficult and enjoyable. You may obtain this through the use of the type() methodology mixed with the Math.random() perform. Right here’s how you are able to do it:

questions.kind(
  perform() { 
    return 0.5 - Math.random();
  }
);

This code will randomly kind the questions array every time the web page is loaded.

How Can I Add a Timer to the Quiz?

Including a timer could make your quiz extra thrilling. You may simply add a timer to the quiz utilizing the JavaScript setInterval() perform. Right here’s a easy instance:

var timeLeft = 30;
var timer = setInterval(perform() { 
  timeLeft--; 
  doc.getElementById('timer').textContent = timeLeft; 
  if (timeLeft <= 0) { 
    clearInterval(timer); 
    alert('Time is up!'); 
  }
}, 1000);

On this instance, the quiz will final for 30 seconds. The timer will replace each second, and when the time is up, an alert can be proven.

How Can I Present the Appropriate Reply if the Consumer Will get it Unsuitable?

You may present the right reply by modifying the checkAnswer() perform. You may add an else clause to the if assertion that checks if the reply is right. Right here’s how you are able to do it:

perform checkAnswer(query, response) { 
  if (query.responses[response].right) { 
    rating++; 
  } else { 
    alert('The right reply is: ' + query.responses.discover(r => r.right).textual content);
  }
}

On this instance, if the person’s reply is wrong, an alert can be proven with the right reply.

How Can I Add Photographs to the Questions?

You may add photographs to your questions by including an ‘picture’ property to the query objects. You may then use this property to show the picture in your HTML. Right here’s an instance:

questions.push({
 textual content: 'What is that this animal?',
 picture: 'elephant.jpg',
 responses: [
 { text: 'Elephant', correct: true },
 { text: 'Lion', correct: false },
 { text: 'Tiger', correct: false },
 { text: 'Bear', correct: false }
 ]
});

In your HTML, you’ll be able to show the picture like this:

<img src="" id="questionImage">

And in your JavaScript, you’ll be able to replace the src attribute of the picture when displaying a brand new query:

doc.getElementById('questionImage').src = query.picture;

On this instance, a picture of an elephant can be displayed when the query is proven.

How Do I Deal with A number of Appropriate Solutions in a JavaScript Quiz?

Dealing with a number of right solutions entails permitting the person to pick a couple of reply and checking if any of the chosen solutions are right. For instance, right here is how one can replace the above showResults() perform to deal with a number of right solutions.

 perform showResults() {
  const answerContainers = quizContainer.querySelectorAll('.solutions');
  let numCorrect = 0;

  myQuestions.forEach((currentQuestion, questionNumber) => {
    const answerContainer = answerContainers[questionNumber];
    const selector = `enter[name=question${questionNumber}]:checked`;
    const userAnswers = Array.from(answerContainer.querySelectorAll(selector)).map(enter => enter.worth);

    if (userAnswers.kind().toString() === currentQuestion.correctAnswers.kind().toString()) {
      numCorrect++;
      answerContainers[questionNumber].fashion.colour = 'lightgreen';
    } else {
      answerContainers[questionNumber].fashion.colour = 'pink';
    }
  });

  resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.size}`;
}

Is It Essential to Preserve Seperate JavaScript File and a CSS File?

Sustaining separate JavaScript and CSS recordsdata shouldn’t be a should. Nonetheless, it’s typically thought of a finest follow because it improves the readability and maintainability of your code.

Yaphi Berhanu is an internet developer who loves serving to folks increase their coding expertise. He writes suggestions and tips at http://simplestepscode.com. In his utterly unbiased opinion, he suggests checking it out.

Community admin & freelance internet developer.

CSS Animationsjameshmodernjs-tutorialsquiz

Tags: CodeJavaScriptQuizSimpleSitePointTutorial
Admin

Admin

Next Post
5 Greatest Buyer Communications Administration Software program I Like

5 Greatest Buyer Communications Administration Software program I Like

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recommended.

Your New AI-Powered Collaborator — SitePoint

Your New AI-Powered Collaborator — SitePoint

July 2, 2025
Gordon Moore and Robert Noyce left which firm to discovered Intel?

Gordon Moore and Robert Noyce left which firm to discovered Intel?

April 30, 2025

Trending.

Industrial-strength April Patch Tuesday covers 135 CVEs – Sophos Information

Industrial-strength April Patch Tuesday covers 135 CVEs – Sophos Information

April 10, 2025
How you can open the Antechamber and all lever places in Blue Prince

How you can open the Antechamber and all lever places in Blue Prince

April 14, 2025
Expedition 33 Guides, Codex, and Construct Planner

Expedition 33 Guides, Codex, and Construct Planner

April 26, 2025
ManageEngine Trade Reporter Plus Vulnerability Allows Distant Code Execution

ManageEngine Trade Reporter Plus Vulnerability Allows Distant Code Execution

June 10, 2025
Wormable AirPlay Flaws Allow Zero-Click on RCE on Apple Units by way of Public Wi-Fi

Wormable AirPlay Flaws Allow Zero-Click on RCE on Apple Units by way of Public Wi-Fi

May 5, 2025

AimactGrow

Welcome to AimactGrow, your ultimate source for all things technology! Our mission is to provide insightful, up-to-date content on the latest advancements in technology, coding, gaming, digital marketing, SEO, cybersecurity, and artificial intelligence (AI).

Categories

  • AI
  • Coding
  • Cybersecurity
  • Digital marketing
  • Gaming
  • SEO
  • Technology

Recent News

Right now’s NYT Connections: Sports activities Version Hints, Solutions for July 5 #285

Right now’s NYT Connections: Sports activities Version Hints, Solutions for July 5 #285

July 5, 2025
Robotic probe rapidly measures key properties of latest supplies | MIT Information

Robotic probe rapidly measures key properties of latest supplies | MIT Information

July 5, 2025
  • About Us
  • Privacy Policy
  • Disclaimer
  • Contact Us

© 2025 https://blog.aimactgrow.com/ - All Rights Reserved

No Result
View All Result
  • Home
  • Technology
  • AI
  • SEO
  • Coding
  • Gaming
  • Cybersecurity
  • Digital marketing

© 2025 https://blog.aimactgrow.com/ - All Rights Reserved