JavaScript Multiple Choice Quiz Questions Code

JavaScript Multiple Choice Questions Code
Code Snippet:Trivia quiz in pure JavaScript
Author: marek
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 21,082
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a multiple choice questions app in your web project. It holds all the questions and possible answers in an object and then loads all the questions into the question area. Users can choose the correct answer and see the result at the end of the quiz.

How to Create JavaScript Multiple Choice Questions Code

1. First of all, create the HTML structure as follows:

<div class="wrapper">
    <div id="quiz">
      <h1>Trivia quiz</h1>
      
      <p class="questions"></p>
      
      <div class="answers"></div>         
      
      <div class="checkAnswers">
        <h3>Correct?</h3>
        <div class="checker">

        </div>
      </div>
    </div>
  </div>  

2. After that, add the following CSS styles to your project:

body, html {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  font-family: 'Roboto', sans-serif;
}

.wrapper {
  width: 430px;
  margin: 0 auto;
  height: 100%;
  padding-top: 0px;
}

#quiz {
  background-color: #34495E;
  padding-bottom: 60px;
  width: 100%;
  border-radius: 2%;
  color: #fff;
  text-align: center;
  box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
}

#quiz > h1 {
  text-align: center;
  padding-top: 25px;
  font-size: 20px;
}

.questions {
  font-size: 28px;
  font-weight: 700;
  font-style: italic;
  border-top: 1px solid #FFFFFF;
  border-bottom: 1px solid #FFFFFF;
  padding: 20px;
}

.answers div {
  padding: 10px 0 0 0;
  font-size: 16px;
}

.answers div:hover {
  cursor: pointer;
  color: #FBCB43;
}

.answers {
  padding: 0px 0 10px 0px;
}

.answers div {
  width: 50%;
  margin: 0 auto;
  padding-bottom: 15px;
  border-top: 1px solid grey;
}

.answers div:first-child {
  border: none;
}

.checker {
  display: inline-block;
  width: 200px;
  margin: 0 auto;
}

.correct, .false {
  background-color: #109D59;
  width: 60px;
  height: 30px;
  line-height: 30px;
  padding-left: 4px;
  float: left;
  margin-left: 2px;
  margin-top: 2px;
}

.false {
  background-color: #DC4437;
}

3. Finally, add the following JavaScript code and done.

window.onload = function () {
  
  var questionArea = document.getElementsByClassName('questions')[0],
      answerArea   = document.getElementsByClassName('answers')[0],
      checker      = document.getElementsByClassName('checker')[0],
      current      = 0,
  
     // An object that holds all the questions + possible answers.
     // In the array --> last digit gives the right answer position
      allQuestions = {
        'What is Canada\'s national animal?' : ['Beaver', 'Duck', 'Horse', 0],
        
        'What is converted into alcohol during brewing?' : ['Grain', 'Sugar' , 'Water', 1],
        
        'In what year was Prince Andrew born? ' : ['1955', '1960', '1970', 1]
      };
      
  function loadQuestion(curr) {
  // This function loads all the question into the questionArea
  // It grabs the current question based on the 'current'-variable
  
    var question = Object.keys(allQuestions)[curr];
    
    questionArea.innerHTML = '';
    questionArea.innerHTML = question;    
  }
  
  function loadAnswers(curr) {
  // This function loads all the possible answers of the given question
  // It grabs the needed answer-array with the help of the current-variable
  // Every answer is added with an 'onclick'-function
  
    var answers = allQuestions[Object.keys(allQuestions)[curr]];
    
    answerArea.innerHTML = '';
    
    for (var i = 0; i < answers.length -1; i += 1) {
      var createDiv = document.createElement('div'),
          text = document.createTextNode(answers[i]);
      
      createDiv.appendChild(text);      
      createDiv.addEventListener("click", checkAnswer(i, answers));
      
      
      answerArea.appendChild(createDiv);
    }
  }
  
  function checkAnswer(i, arr) {
    // This is the function that will run, when clicked on one of the answers
    // Check if givenAnswer is sams as the correct one
    // After this, check if it's the last question:
    // If it is: empty the answerArea and let them know it's done.
    
    return function () {
      var givenAnswer = i,
          correctAnswer = arr[arr.length-1];
      
      if (givenAnswer === correctAnswer) {
        addChecker(true);             
      } else {
        addChecker(false);                        
      }
      
      if (current < Object.keys(allQuestions).length -1) {
        current += 1;
        
        loadQuestion(current);
        loadAnswers(current);
      } else {
        questionArea.innerHTML = 'Done';
        answerArea.innerHTML = '';
      }
                              
    };
  }
  
  function addChecker(bool) {
  // This function adds a div element to the page
  // Used to see if it was correct or false
  
    var createDiv = document.createElement('div'),
        txt       = document.createTextNode(current + 1);
    
    createDiv.appendChild(txt);
    
    if (bool) {
      
      createDiv.className += 'correct';
      checker.appendChild(createDiv);
    } else {
      createDiv.className += 'false';
      checker.appendChild(createDiv);
    }
  }
  
  
  // Start the quiz right away
  loadQuestion(current);
  loadAnswers(current);
  
};

That’s all! hopefully, you have successfully integrated this multiple choice questions code snippet into your project. If you have any questions or facing any issues, feel free to comment below.

4 thoughts on “JavaScript Multiple Choice Quiz Questions Code”

  1. Hi marek
    It is Peter over here, I really like you code but I have some questions it has more than one question and only let me pick one answer, and would like to make the code when a hit the wrong answer it give me the answer

    Thanks

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X