Javascript Multiple Choice Quiz Code For Blogger

0

Javascript multiple choice quiz code

Javascript multiple choice quiz code suitable for all websites, even ideal for blogger websites, here is the quiz code with HTML quiz code to make MCQs (Multiple Choice Questions)

Usually, blogger websites support only HTML, JavaScript and CSS codes which are allowed to display any information, HTML, and JavaScript quiz code is given in this article as the script.

Here some of the best Javascript multiple choice quiz code given below. You Can copy them and use in your website or blogger for free.

1.JS Quiz

Javascript Multiple Choice Quiz Code For Blogger

Code Of JS Quiz


HTML
<header class="header bg-primary"><div class="left-title">JS Quiz</div><div class="right-title">Total Questions: <span id="tque"></span></div>
<div class="clearfix"></div>
</header>
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-sm-12">
<div id="result" class="quiz-body">
<form name="quizForm" onSubmit="">
              <fieldset class="form-group">
          <h4><span id="qid">1.</span> <span id="question"></span></h4>
                <div class="option-block-container" id="question-options">
                  </div> <!-- End of option block -->
                 </fieldset>
                 <button  name="previous" id="previous" class="btn btn-success">Previous</button>
                 &nbsp;
                 <button  name="next" id="next" class="btn btn-success">Next</button>
           </form>
           </div>
        </div> <!-- End of col-sm-12 -->
        
    </div> <!-- End of row -->
</div> <!-- ENd of container fluid -->
</div> <!-- End of content -->
<style>.content { margin-top:54px; }
.header {padding:15px; position:fixed; top:0; width:100%; z-index:9999; }
.left-title { width:80px; color:#FFF; font-size:18px; float:left; }
.right-title { width:150px; text-align:right; float:right; color:#FFF;  }
.quiz-body { margin-top:15px; padding-bottom:50px; }
.option-block-container { margin-top:20px; max-width:420px; }
.option-block { padding:10px; background:aliceblue; border:1px solid #84c5fe; margin-bottom:10px; cursor:pointer; }
.result-question { font-weight:bold; }
.c-wrong { margin-left:20px; color:#FF0000; }
.c-correct {  margin-left:20px; color:green; }
.last-row { border-bottom:1px solid #ccc; padding-bottom:25px; margin-bottom:25px; }
.res-header { border-bottom:1px solid #ccc; margin-bottom:15px; padding-bottom:15px; }</style>
<script type="text/javascript">/* Created and coded by Abhilash Narayan */
/* Quiz source: w3schools.com */ var quiz = { "JS" : [
  {
    "id" : 1,
    "question" : "Inside which HTML element do we put the JavaScript?",
    "options" : [
      {"a": "&lt;script&gt;", 
       "b":"&lt;javascript&gt;", 
       "c":"&lt;scripting&gt;", 
       "d":"&lt;js&gt;"}
      ],
    "answer":"&lt;script&gt;",
    "score":0,
    "status": ""
  },
  {
    "id" : 2,
    "question" : "Where is the correct place to insert a JavaScript?",
    "options" : [
      {"a": "The &lt;head&gt; section", 
       "b":"The &lt;body&gt; section", 
       "c":"Both the &lt;head&gt; section and the &lt;body&gt; section are correct"}
      ],
    "answer":"Both the &lt;head&gt; section and the &lt;body&gt; section are correct",
    "score":0,
    "status": ""
  },
  {
    "id" : 3,
    "question" : "What is the correct syntax for referring to an external script called 'xxx.js'?",
    "options" : [
      {"a": "&ltscript href=&quot;xxx.js&quot;>", 
       "b":"&lt;script name=&quot;xxx.js&quot;&gt;", 
       "c":"&lt;script src=&quot;xxx.js&quot;&gt;"}
      ],
    "answer":"&lt;script src=&quot;xxx.js&quot;&gt;",
    "score":0,
    "status": ""
  },
  {
    "id" : 4,
    "question" : "The external JavaScript file must contain the &lt;script&gt; tag.",
    "options" : [
      {"a": "True", 
       "b":"False"
      }
      ],
    "answer":"False",
    "score":0,
    "status": ""
  },
  {
    "id" : 5,
    "question" : "How do you write &quot;Hello World&quot; in an alert box?",
    "options" : [
      {"a": "alertBox(&quot;Hello World&quot;);", 
       "b":"msg(&quot;Hello World&quot;);",
       "c":"alert(&quot;Hello World&quot;);",
       "d":"msgBox(&quot;Hello World&quot;);",
      }
      ],
    "answer":"alert(&quot;Hello World&quot;);",
    "score":0,
    "status": ""
  },
  {
    "id" : 6,
    "question" : "How do you create a function in JavaScript?",
    "options" : [
      {"a": "function myFunction()", 
       "b":"function:myFunction()",
       "c":"function = myFunction()",
      }
      ],
    "answer":"function myFunction()",
    "score":0,
    "status": ""
  },
  {
    "id" : 7,
    "question" : "How do you call a function named &quot;myFunction&quot;?",
    "options" : [
      {"a": "call function myFunction()", 
       "b":"call myFunction()",
       "c":"myFunction()",
      }
      ],
    "answer":"myFunction()",
    "score":0,
    "status": ""
  },
  {
    "id" : 8,
    "question" : "How to write an IF statement in JavaScript?",
    "options" : [
      {"a": "if i = 5 then", 
       "b":"if i == 5 then",
       "c":"if (i == 5)",
       "d":" if i = 5",
      }
      ],
    "answer":"if (i == 5)",
    "score":0,
    "status": ""
  },
  {
    "id" : 9,
    "question" : "Which of the following is a disadvantage of using JavaScript?",
    "options" : [
      {"a": "Client-side JavaScript does not allow the reading or writing of files.", 
       "b":"JavaScript can not be used for Networking applications because there is no such support available.",
       "c":"JavaScript doesn't have any multithreading or multiprocess capabilities.",
       "d":"All of the above."
      }
      ],
    "answer":"All of the above.",
    "score":0,
    "status": ""
  },
  {
    "id" : 10,
    "question" : "How to write an IF statement for executing some code if &quot;i&quot; is NOT equal to 5?",
    "options" : [
      {"a": "if (i <> 5)", 
       "b":"if i <> 5",
       "c":"if (i != 5)",
       "d":"if i =! 5 then",
      }
      ],
    "answer":"if (i != 5)",
    "score":0,
    "status": ""
  },
  {
    "id" : 11,
    "question" : "How does a WHILE loop start?",
    "options" : [
      {"a": "while i = 1 to 10", 
       "b":"while (i &lt;= 10; i++)",
       "c":"while (i &lt;= 10)"
      }
      ],
    "answer":"while (i &lt;= 10)",
    "score":0,
    "status": ""
  },
  {
    "id" : 12,
    "question" : "How does a FOR loop start?",
    "options" : [
      {"a": "for (i = 0; i &lt;= 5)", 
       "b":"for (i = 0; i &lt;= 5; i++)",
       "c":"for i = 1 to 5",
       "d":"for (i &lt;= 5; i++)"
      }
      ],
    "answer":"for (i = 0; i &lt;= 5; i++)",
    "score":0,
    "status": ""
  },
  {
    "id" : 13,
    "question" : "How can you add a comment in a JavaScript?",
    "options" : [
      {"a": "//This is a comment", 
       "b":"&sbquo;This is a comment",
       "c":"&lt;!--This is a comment--&gt;"
      }
      ],
    "answer":"//This is a comment",
    "score":0,
    "status": ""
  },
  {
    "id" : 14,
    "question" : "How to insert a comment that has more than one line?",
    "options" : [
      {"a": "/*This comment has more than one line*/", 
       "b":"//This comment has more than one line//",
       "c":"&lt;!--This comment has more than one line--&gt;"
      }
      ],
    "answer":"/*This comment has more than one line*/",
    "score":0,
    "status": ""
  },
  {
    "id" : 15,
    "question" : "What is the correct way to write a JavaScript array?",
    "options" : [
      {"a": "var colors = (1:&quot;red&quot;, 2:&quot;green&quot;, 3:&quot;blue&quot;)", 
       "b":"var colors = [&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;]",
       "c":"var colors = 1 = (&quot;red&quot;), 2 = (&quot;green&quot;), 3 = (&quot;blue&quot;)",
       "d":"var colors = &quot;red&quot;, &quot;green&quot;, &quot;blue&quot;"
      }
      ],
    "answer":"var colors = [&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;]",
    "score":0,
    "status": ""
  },
  {
    "id" : 16,
    "question" : "How do you round the number 7.25, to the nearest integer?",
    "options" : [
      {"a": "rnd(7.25)", 
       "b":"Math.round(7.25)",
       "c":"Math.rnd(7.25)",
       "d":"round(7.25)"
      }
      ],
    "answer":"Math.round(7.25)",
    "score":0,
    "status": ""
  },
  {
    "id" : 17,
    "question" : "How do you find the number with the highest value of x and y?",
    "options" : [
      {"a": "Math.max(x, y)", 
       "b":"Math.ceil(x, y)",
       "c":"top(x, y)",
       "d":"ceil(x, y)"
      }
      ],
    "answer":"Math.max(x, y)",
    "score":0,
    "status": ""
  },
  {
    "id" : 18,
    "question" : "What is the correct JavaScript syntax for opening a new window called &quot;w2&quot;?",
    "options" : [
      {"a": "w2 = window.new(&quot;http://www.w3schools.com&quot;);", 
       "b":"w2 = window.open(&quot;http://www.w3schools.com&quot;);"       }
      ],
    "answer":"w2 = window.open(&quot;http://www.w3schools.com&quot;);",
    "score":0,
    "status": ""
  },
  {
    "id" : 19,
    "question" : "JavaScript is the same as Java.",
    "options" : [
      {"a": "true", 
       "b":"false"       }
      ],
    "answer":"false",
    "score":0,
    "status": ""
  },
  {
    "id" : 20,
    "question" : "How can you detect the client&rsquo;s browser name?",
    "options" : [
      {"a": "navigator.appName", 
       "b":"browser.name",
       "c":"client.navName"
      }
      ],
    "answer":"navigator.appName",
    "score":0,
    "status": ""
  },
  {
    "id" : 21,
    "question" : "Which event occurs when the user clicks on an HTML element?",
    "options" : [
      {"a": "onchange", 
       "b":"onclick",
       "c":"onmouseclick",
       "d":"onmouseover"
      }
      ],
    "answer":"onclick",
    "score":0,
    "status": ""
  },
  {
    "id" : 22,
    "question" : "How do you declare a JavaScript variable?",
    "options" : [
      {"a": "var carName;", 
       "b":"variable carName;",
       "c":"v carName;"
      }
      ],
    "answer":"var carName;",
    "score":0,
    "status": ""
  },
  {
    "id" : 23,
    "question" : "Which operator is used to assign a value to a variable?",
    "options" : [
      {"a": "*", 
       "b":"-",
       "c":"=",
       "d":"x"
      }
      ],
    "answer":"=",
    "score":0,
    "status": ""
  },
  {
    "id" : 24,
    "question" : "What will the following code return: Boolean(10 &gt; 9)",
    "options" : [
      {"a": "NaN", 
       "b":"false",
       "c":"true"
      }
      ],
    "answer":"true",
    "score":0,
    "status": ""
  },
  {
    "id" : 25,
    "question" : "Is JavaScript case-sensitive?",
    "options" : [
      {"a": "No", 
       "b":"Yes"
      }
      ],
    "answer":"Yes",
    "score":0,
    "status": ""
  }
  ]
} var quizApp = function() {   this.score = 0;   
  this.qno = 1;
  this.currentque = 0;
  var totalque = quiz.JS.length;   
  this.displayQuiz = function(cque) {
    this.currentque = cque;
    if(this.currentque <  totalque) {
      $("#tque").html(totalque);
      $("#previous").attr("disabled", false);
      $("#next").attr("disabled", false);
      $("#qid").html(quiz.JS[this.currentque].id + '.');
  
      
      $("#question").html(quiz.JS[this.currentque].question); 
       $("#question-options").html("");
      for (var key in quiz.JS[this.currentque].options[0]) {
        if (quiz.JS[this.currentque].options[0].hasOwnProperty(key)) {
    
        $("#question-options").append(
          "<div class='form-check option-block'>" +
          "<label class='form-check-label'>" +
                "<input type='radio' class='form-check-input' name='option'   id='q"+key+"' value='" + quiz.JS[this.currentque].options[0][key] + "'><span id='optionval'>" +
                  quiz.JS[this.currentque].options[0][key] +
               "</span></label>"
        );
        }
      }
    }
    if(this.currentque <= 0) {
      $("#previous").attr("disabled", true);  
    }
    if(this.currentque >= totalque) {
        $('#next').attr('disabled', true);
        for(var i = 0; i < totalque; i++) {
          this.score = this.score + quiz.JS[i].score;
        }
      return this.showResult(this.score); 
    }
  }
  
  this.showResult = function(scr) {
    $("#result").addClass('result');
    $("#result").html("<h1 class='res-header'>Total Score: &nbsp;" + scr  + '/' + totalque + "</h1>");
    for(var j = 0; j < totalque; j++) {
      var res;
      if(quiz.JS[j].score == 0) {
          res = '<span class="wrong">' + quiz.JS[j].score + '</span><i class="fa fa-remove c-wrong"></i>';
      } else {
        res = '<span class="correct">' + quiz.JS[j].score + '</span><i class="fa fa-check c-correct"></i>';
      }
      $("#result").append(
      '<div class="result-question"><span>Q ' + quiz.JS[j].id + '</span> &nbsp;' + quiz.JS[j].question + '</div>' +
      '<div><b>Correct answer:</b> &nbsp;' + quiz.JS[j].answer + '</div>' +
      '<div class="last-row"><b>Score:</b> &nbsp;' + res +
      
      '</div>' 
      
      );
      
    }
  }
  
  this.checkAnswer = function(option) {
    var answer = quiz.JS[this.currentque].answer;
    option = option.replace(/\</g,"&lt;")   //for <
    option = option.replace(/\>/g,"&gt;")   //for >
    option = option.replace(/"/g, "&quot;")     if(option ==  quiz.JS[this.currentque].answer) {
      if(quiz.JS[this.currentque].score == "") {
        quiz.JS[this.currentque].score = 1;
        quiz.JS[this.currentque].status = "correct";
    }
    } else {
      quiz.JS[this.currentque].status = "wrong";
    }
    
  } 
   
  this.changeQuestion = function(cque) {
      this.currentque = this.currentque + cque;
      this.displayQuiz(this.currentque);  
      
  }
  
}
var jsq = new quizApp(); var selectedopt;
  $(document).ready(function() {
      jsq.displayQuiz(0);   
    
  $('#question-options').on('change', 'input[type=radio][name=option]', function(e) {       //var radio = $(this).find('input:radio');
      $(this).prop("checked", true);
        selectedopt = $(this).val();
    });
    
      
       
  });   
  
  
  $('#next').click(function(e) {
      e.preventDefault();
      if(selectedopt) {
        jsq.checkAnswer(selectedopt);
      }
      jsq.changeQuestion(1);
  }); 
  
  $('#previous').click(function(e) {
    e.preventDefault();
    if(selectedopt) {
      jsq.checkAnswer(selectedopt);
    }
      jsq.changeQuestion(-1);
  });  </script>
Note: Copy the above quiz code and paste it into your blogger or website page. 

For bloggers, you have to switch the HTML view from composing view to insert the code

2.Quiz-App using HTML,CSS,JS

Javascript Multiple Choice Quiz Code For Blogger

Code Of Quiz-App using HTML,CSS,JS



HTML
  <script src="https://kit.fontawesome.com/b91379b65b.js" crossorigin="anonymous"></script>
  <div class="quiz-container" id="quiz">
    <div class="quiz-header">
      <h2 id="question">Question is loading...</h2>
      <ul>
        <li>
          <input type="radio" name="answer" id="a" class="answer" />
          <label for="a" id="a_text">Answer...</label>
        </li>
        <li>
          <input type="radio" name="answer" id="b" class="answer" />
          <label for="b" id="b_text">Answer...</label>
        </li>
        <li>
          <input type="radio" name="answer" id="c" class="answer" />
          <label for="c" id="c_text">Answer...</label>
        </li>
        <li>
          <input type="radio" name="answer" id="d" class="answer" />
          <label for="d" id="d_text">Answer...</label>
        </li>
      </ul>
    </div>
    <button id="submit">Submit</button>
  </div>
  <script src="app.js"></script>
  <style type="text/css">@import url("https://fonts.googleapis.com/css2?family=Poppins:[email protected];400&display=swap") * {
  box-sizing: border-box;
} body {
  background-color: #b8c6db;
  background-image: linear-gradient(315deg, #b8c6db 0%, #f5f7fa 100%);
  font-family: "Poppins", sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  overflow: hidden;
  margin: 0;
} input {
  cursor: pointer;
} .quiz-container {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 0 10px 2px rgba(100, 100, 100, 0.1);
  width: 600px;
  max-width: 95vw;
  overflow: hidden;
} .quiz-header {
  padding: 4rem;
} h2 {
  padding: 1rem;
  text-align: center;
  margin: 0;
} ul {
  list-style-type: none;
  padding: 0;
} ul li {
  font-size: 1.2rem;
  margin: 1rem 0;
} button {
  background-color: #781c68;
  color: #fff;
  border: none;
  display: block;
  width: 100%;
  cursor: pointer;
  font-size: 1.1rem;
  font-family: inherit;
  padding: 1.3rem;
} button:hover {
  background-color: #293462;
} button:focus {
  outline: none;
  background-color: #5e3370;
}
</style>
<script type="text/javascript">const quizData = [
  {
    question: "Which language runs in a web browser?",
    a: "Java",
    b: "C",
    c: "Python",
    d: "JavaScript",
    correct: "d"
  },
  {
    question: "What does CSS stand for?",
    a: "Central Style Sheets",
    b: "Cascading Style Sheets",
    c: "Cascading Simple Sheets",
    d: "Cars SUVs Sailboats",
    correct: "b"
  },
  {
    question: "What does HTML stand for?",
    a: "Hypertext Markup Language",
    b: "Hypertext Markdown Language",
    c: "Hyperloop Machine Language",
    d: "Helicopters Terminals Motorboats Lamborginis",
    correct: "a"
  },
  {
    question: "What year was JavaScript launched?",
    a: "1996",
    b: "1995",
    c: "1994",
    d: "none of the above",
    correct: "b"
  },
  {
    question: "Is javaScript is programming language?",
    a: "Yes",
    b: "No",
    c: "Not sure",
    d: "none of the above",
    correct: "a"
  },
  {
    question: "How we can alert hello world?",
    a: "alertbox('hello world')",
    b: "alert('hello world')",
    c: "myalert('hello world')",
    d: "none of the above",
    correct: "b"
  },
  {
    question: "HTML is used for?",
    a: "Build the Website/App",
    b: "Programming",
    c: "Hacking",
    d: "none of the above",
    correct: "a"
  },
  {
    question: "Best place to add script tag in HTML?",
    a: "Head",
    b: "Body",
    c: "Bottom of the HTML",
    d: "Both A and B",
    correct: "d"
  },
  {
    question: "Coding is?",
    a: "Art",
    b: "Science",
    c: "Headache",
    d: "Both A and B",
    correct: "d"
  },
  {
    question: "Who's your Saylani",
    a: "Sir Kashif suleman",
    b: "Sir Rizwan",
    c: "None of Them",
    d: "Both A and B",
    correct: "a"
  }
]; const quiz = document.getElementById("quiz");
const answerElements = document.querySelectorAll(".answer");
const questionElement = document.getElementById("question");
const a_text = document.getElementById("a_text");
const b_text = document.getElementById("b_text");
const c_text = document.getElementById("c_text");
const d_text = document.getElementById("d_text");
const submitButton = document.getElementById("submit"); let currentQuiz = 0;
let score = 0; const deselectAnswers = () => {
  answerElements.forEach((answer) => (answer.checked = false));
}; const getSelected = () => {
  let answer;
  answerElements.forEach((answerElement) => {
    if (answerElement.checked) answer = answerElement.id;
  });
  return answer;
}; const loadQuiz = () => {
  deselectAnswers();
  const currentQuizData = quizData[currentQuiz];
  questionElement.innerText = currentQuizData.question;
  a_text.innerText = currentQuizData.a;
  b_text.innerText = currentQuizData.b;
  c_text.innerText = currentQuizData.c;
  d_text.innerText = currentQuizData.d;
}; loadQuiz(); submitButton.addEventListener("click", () => {
  const answer = getSelected();
  if (answer) {
    if (answer === quizData[currentQuiz].correct) score++;
    currentQuiz++;
    if (currentQuiz < quizData.length) loadQuiz();
    else {
      quiz.innerHTML = `
            <h2>You answered ${score}/${quizData.length} questions correctly</h2>
            <button onclick="history.go(0)">Play Again</button>
        `;
    }
  }
});
</script>

Note: Copy the above quiz code and paste it into your blogger or website page. 

For bloggers, you have to switch the HTML view from composing view to insert the code

3.Quiz Code With Timer

Javascript Multiple Choice Quiz Code

Code Of Quiz App With Timer


HTML
<div class="start-screen">
  <button id="start-button">Start</button>
</div>
<div id="wrapper">
  <div id="display-container">
    <div class="header">
      <div class="number-of-count">
        <span class="number-of-question"></span>
      </div>
      <div class="timer-div">
        <img src="https://svgshare.com/i/iRM.svg" />
        <span class="time-left"></span>
      </div>
    </div>
    <div id="container">
      <!-- Question and options are displayed here -->
    </div>
    <div class="btn-container">
      <button id="next-button">Next</button>
    </div>
  </div>
  <a href="https://youtu.be/p-2G-7vLuV4" target="_blank">Watch Me Code &nbsp;<i class="fab fa-youtube"></i></a>
</div>
<div class="score-container hide">
  <div id="user-score"></div>
  <button id="restart">Restart</button>
</div>
<style type="text/css">* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
  -webkit-tap-highlight-color: transparent;
}
body {
  background-color: #0a69ed;
}
.start-screen,
.score-container {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
button {
  border: none;
  outline: none;
  cursor: pointer;
}
#start-button,
#restart {
  font-size: 1.3em;
  padding: 0.5em 1.8em;
  border-radius: 0.2em;
}
#restart {
  margin-top: 0.9em;
}
#wrapper {
  position: absolute;
  transform: translateX(-50%);
  top: 20px;
  left: 50%;
  width: 90%;
  max-width: 37.5em;
}
#display-container {
  position: relative;
  background-color: #ffffff;
  padding: 3.1em 1.8em;
  width: 100%;
  margin: 0 auto;
  border-radius: 0.6em;
  box-shadow: 0 20px 45px rgba(0, 24, 56, 0.15);
}
a {
  display: block;
  background-color: #ffffff;
  position: relative;
  margin-top: 1em;
  text-align: center;
  text-decoration: none;
  color: #0a69ed;
  font-size: 1.4em;
  font-weight: 600;
  padding: 1em 0;
  border-radius: 0.4em;
  box-shadow: 0 20px 45px rgba(0, 24, 56, 0.15);
}
.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: 500;
}
.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: #0b012d;
  cursor: not-allowed;
}
.btn-container {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 1.5em;
}
#next-button {
  font-size: 1em;
  background-color: #0a69ed;
  color: #ffffff;
  padding: 0.7em 1.8em;
  border-radius: 0.3em;
}
.hide {
  display: none;
}
.correct {
  background-color: #e7f6d5;
  color: #689f38;
  border-color: #689f38;
}
.inCorrect {
  background-color: #ffdde0;
  color: #d32f2f;
  border-color: #d32f2f;
}
#user-score {
  font-size: 1.5em;
  color: #ffffff;
}
i.fab {
  color: #ff0000;
}
@media screen and (max-width: 600px) {
  body {
    font-size: 12px;
  }
}
</style>
<script type="text/javascript">// References
const quizdisplay = document.getElementById("display");
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 wrapper = document.getElementById("wrapper");
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; //Question and Options array
// Add questions, options and correct option in below format
const quizArray = [
  {
    id: "0",
    question: "For every one person, there are 1.6 million ____",
    options: ["Websites", "Grain Of Sands", "Ants", "Rodents"],
    correct: "Ants"
  },
  {
    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"
  }
];
// restart game
restart.addEventListener("click", () => {
  inital(); //call initial function
  wrapper.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
      wrapper.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 (so that it starts with 10)
      count = 11;
      //clear interval for next question
      clearInterval(countdown);
      //display timer (start countdown)
      timerDisplay();
    }
  })
);
// Timer
const timerDisplay = () => {
  countdown = setInterval(() => {
    count--;
    timeLeft.innerHTML = `${count}s`;
    if (count == 0) {
      //when countdown reaches 0 clearInterval and go to next question
      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);
  }
}
// Check 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's clicked anaswer==correct option stored in object
  if (userSolution === quizArray[questionCount].correct) {
    //green background and score increment
    userOption.classList.add("correct");
    scoreCount++;
  } else {
    //red background
    userOption.classList.add("inCorrect");
    //for marking green(correct)
    options.forEach((element) => {
      if (element.innerText == quizArray[questionCount].correct) {
        element.classList.add("correct");
      }
    });
  }
  //clear interval(stop timer)
  clearInterval(countdown);
  //disabled all options
  options.forEach((element) => {
    element.disabled = true;
  });
}
//initial setup
function inital() {
  quizContainer.innerHTML = "";
  questionCount = 0;
  scoreCount = 0;
  clearInterval(countdown);
  count = 11;
  timerDisplay();
  quizCreator();
  quizDisplay(questionCount);
}
// when user click on start button
startButton.addEventListener("click", () => {
  startScreen.classList.add("hide");
  wrapper.classList.remove("hide");
  inital();
});
//hide quiz and display start screen
window.onload = () => {
  startScreen.classList.remove("hide");
  wrapper.classList.add("hide");
};
</script>

Note: Copy the above quiz code and paste it into your blogger or website page. 

For bloggers, you have to switch the HTML view from composing view to insert the code

4.Quiz JS

Javascript Multiple Choice Quiz Code

Code Of QUIZ JS For Blogger


HTML
<!-- header start butoon  -->
    <header class="start">
      <button id="start_quiz">Start Quiz</button>
    </header>
    <!-- quiz box -->
    <section class="quiz_container">
      <div class="quiz_text">
        <h1>HTML Multiple choice questions (MCQ's)</h1>
      </div>       <div class="quiz_box">
        <div class="quiz_question"></div>
        <div class="options"></div>
      </div>       <footer>
        <div class="question_no"></div>
        <div class="buttons">
          <button class="btn" id="next">Next</button>
        </div>
      </footer>
    </section>     <article class="result_box">
      <div class="score"></div>
      <button id="replay" class="btn">Replay Quiz</button>
    </article>
<style type="text/css">@import url('https://fonts.googleapis.com/css2?family=Roboto&family=Tiro+Bangla&display=swap'); :root {
  --body-bg: #d99e55;
  ;
  --start_quiz-c: #1d9eab;
  --white: #fff;
  --bg-button: #e0e0e0;
  --right: #87e487;
  --wrong: #f19a9a;
} * {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
} body {
  font-family: 'Roboto', sans-serif;
  height: 100vh;
  background-color: var(--body-bg);
} input,
button,
h1 ,
span{
  outline: 0;
  border: 0;
  font-family: inherit;
} /* center all box  */
.start,
.quiz_container,
.result_box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 12px;
  background: var(--white);
  box-shadow: 15px 15px 24px #bd986a, -15px -15px 20px #bd986a;
} /* start button  */
.start #start_quiz {
  padding: 15px;
  border-radius: 10px;
  color: var(--start_quiz-c);
  font-size: 2rem;
  cursor: pointer;
} /* quiz box  */
.quiz_container {
  border-radius: 20px;
  padding: 20px;
  width: 600px;
  display: none;
} /* quiz_text  */
.quiz_container .quiz_text {
  margin-bottom: 20px;
} .quiz_container .quiz_text h1 {
  font-size: 1.5rem;
  letter-spacing: 2px;
  text-align: center;
} /* quiz_box  */
.quiz_box {
  padding: 10px 5px;
} .quiz_box .quiz_question h1 {
  font-size: 1.1rem;
} .quiz_box .quiz_question p {
  display: inline;
} /* options  */
.option_list {
  margin-top: 15px;
  font-size: 1rem;
  padding: 5px 15px;
  background-color: var(--bg-button);
  border-radius: 5px;
  cursor: pointer;
  transition: 0.5s ease;
  user-select: none;
  box-shadow: 1px 1px 8px #bebebe, -1px -1px 20px #ffffff
} .options .option_list:hover {
  background-color: var(--start_quiz-c);
} .options .option_list.correct {
  background-color: var(--right);
} .options .option_list.wrong {
  background-color: var(--wrong);
} .disabled {
  pointer-events: none;
} /* footer  */
footer {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  user-select: none; } .center {
  display: flex;
  font-size: 0.9rem;
  margin-left: 6px;
} footer .buttons {
  margin-right: 6px;
} .btn {
  padding: 7px 15px;
  border-radius: 10px;
  background: var(--start_quiz-c);
  color: var(--white);
  font-size: 1rem;
  cursor: pointer;
} /* score  */
.result_box {
  display: none;
  padding: 20px;
  text-align: center;
} .score span {
  margin: 15px 0;
  display: flex;
  justify-content: center;
  font-size: 1rem;
  font-weight: 600;
} span p {
  padding: 0 5px;
}</style>
<script type="text/javascript">const questions = [
    {
        'id': 1,
        "question": 'HTML stands for?',
        'Options': [
            'HighText Machine Language',
            'HyperText and links Markup Language',
            'HyperText Markup Language',
            'None of these'
        ],
        'answer': 'HyperText Markup Language'
    },
    {
        'id': 2,
        "question": 'What is the smallest header in HTML by default?',
        'Options': [
            'h1',
            'h2',
            'h6',
            'h4'
        ],
        'answer': 'h6'
    },
    {
        'id': 3,
        "question": 'The correct sequence of HTML tags for starting a webpage is -',
        'Options': [
            'Head, Title, HTML, body',
            'HTML, Body, Title, Head',
            'HTML, Head, Body, Title',
            'HTML, Head, Title, Body'
        ],
        'answer': 'HTML, Head, Title, Body'
    },
    {
        'id': 4,
        "question": 'Which of the following attribute is used to provide a unique name to an element?',
        'Options': [
            'class',
            'id',
            'type',
            'None of the above'
        ],
        'answer': 'id'
    },
    {
        'id': 5,
        "question": 'How to create an unordered list (a list with the list items in bullets) in HTML?',
        'Options': [
            '&lt;ul&gt;',
            '&lt;ol&gt;',
            '&lt;li&gt;',
            '&lt;i&gt;'
        ],
        'answer': '&lt;ul&gt;'
    },
    {
        'id': 6,
        "question": 'Which character is used to represent the closing of a tag in HTML?',
        'Options': [
            '/',
            '!',
            '.',
            '&'
        ],
        'answer': '/'
    },
    {
        'id': 7,
        "question": ' How to add a background color in HTML?',
        'Options': [
            '&lt;marquee bg color: "red"&gt;',
            '&lt;marquee bg-color = "red"&gt;',
            '&lt;marquee bgcolor = "red"&gt;',
            '&lt;marquee color = "red"&gt;'
        ],
        'answer': '&lt;marquee bgcolor = "red"&gt;'
    },
    {
        'id': 8,
        "question": 'How to create a checkbox in HTML?',
        'Options': [
            '&lt;input type = "checkbox"&gt;',
            '&lt;input type = "button"&gt;',
            '&lt;checkbox&gt;',
            '&lt;input type = "check"&gt;'
        ],
        'answer': '&lt;input type = "checkbox"&gt;'
    },
    {
        'id': 9,
        "question": '&lt;input&gt; is -',
        'Options': [
            'a format tag.',
            'an empty tag.',
            'All of the above',
            'None of the above'
        ],
        'answer': 'an empty tag.'
    },
    {
        'id': 10,
        "question": 'The &lt;hr&gt; tag in HTML is used for -',
        'Options': [
            'new line',
            'vertical ruler',
            'new paragraph',
            'horizontal ruler'
        ],
        'answer': 'horizontal ruler'
    } ] const start_quiz = document.querySelector('#start_quiz');
const container = document.querySelector('.quiz_container');
const result_box = document.querySelector('.result_box');
const next = document.querySelector('#next');
const section_next = document.querySelector('.ques');
const replay = document.querySelector('#replay');
const options = document.querySelector('.options');
const buttons = document.querySelector('.buttons'); // start_quiz button event 
start_quiz.addEventListener('click', () => {
    start_quiz.style.display = 'none';
    container.style.display = 'block';
    show_question(0);
    buttons.classList.add('disabled'); }) // replay button event 
replay.addEventListener('click', () => {
    start_quiz.style.display = 'block';
    result_box.style.display = 'none';
    active = 0;
    userscore = 0;
    show_question(active);
    options.classList.remove('disabled');
}) // next button event 
let active = 0; // question index number
next.addEventListener('click', () => {
    if (active < questions.length - 1) {
        active++;
        show_question(active);
        options.classList.remove('disabled');
        buttons.classList.add('disabled')
    }
    else {
        result_box.style.display = 'block';
        container.style.display = 'none'
        result(); //result function 
    }
}) // show_question function 
let userscore = 0; // correct answer select by user
function show_question(index) {
    // question name 
    const quiz_question = document.querySelector('.quiz_question');
    quiz_question.innerHTML = `<h1><p>${questions[index].id}. </p>${questions[index].question}</h1>`
    //  question option list 
    options.innerHTML = `<div class="option_list">${questions[index].Options[0]}</div>
    <div class="option_list">${questions[index].Options[1]}</div>
    <div class="option_list">${questions[index].Options[2]}</div>
    <div class="option_list">${questions[index].Options[3]}</div>`
    // current number of question
    const question_no = document.querySelector('.question_no');
    question_no.innerHTML = `<span class="center"><p>${questions[index].id}</p>of<p>${questions.length}</p>Questions</span>`     const options_list = document.querySelectorAll('.option_list');
    options_list.forEach((e) => {
        e.addEventListener('click', (op) => {
            if (op.target.innerHTML == questions[active].answer) {
                console.log(op.target.innerHTML);
                userscore++; //userscore incresed by correct answer
                e.classList.add('correct');
                options.classList.add('disabled');
                buttons.classList.remove('disabled');
            }             else {
                e.classList.add('wrong');
                options.classList.add('disabled');
                buttons.classList.remove('disabled');
                // if wrong answer selected then correct class added correct answer 
                for (let i = 0; i < options.children.length; i++) {
                    if (options.children[i].innerHTML == questions[active].answer) {
                        options.children[i].classList.add('correct');
                    }
                }
            }
        })
    })
} function result() {
    const score = document.querySelector('.score');
    score.innerHTML = `<h1>Your Score is</h1><span><p>${userscore}</p>of<p>${questions.length}</p></span>`
} </script>

Note: Copy the above quiz code and paste it into your blogger or website page. 

For bloggers, you have to switch the HTML view from composing view to insert the code.

5.SIMPLE JS QUIZ

Javascript Multiple Choice Quiz Code

Code Of SIMPLE JS QUIZ For Blogger


HTML
<div class="widget-wrap">
  <h1>SIMPLE JS QUIZ</h1>
  
  <!-- (A) QUIZ CONTAINER -->
  <div id="quizWrap"></div>
  
  <!-- (X) VISIT CODE-BOXX -->
  <div id="code-boxx">
    Visit
    <a href="https://code-boxx.com/simple-javascript-quiz/" target="_blank">
      Code Boxx
    </a> for more details.
  </div>
</div>
<style type="text/css">/* (A) WRAPPER */
#quizWrap {
  max-width: 600px;
  margin: 0 auto;
  /* RECOMMENDED FIXED HEIGHT IF YOU HAVE CONTENT BELOW THE QUIZ */
  /* SO THAT PAGE LAYOUT DOES NOT "JUMP" */
  /* height: 250px; */
} /* (B) QUESTION */
#quizQn {
  padding: 20px;
  background: #4c93ba;
  color: #fff;
  font-size: 24px;
  border-radius: 10px;
} /* (C) ANSWERS */
#quizAns {
  margin: 10px 0;
  display: grid;
  grid-template-columns: auto auto;
  grid-gap: 10px;
}
#quizAns input[type=radio] { display: none; }
#quizAns label {
  background: #fafafa;
  border: 1px solid #eee;
  border-radius: 10px;
  padding: 10px;
  font-size: 20px;
  cursor: pointer;
  text-align: center;
}
#quizAns label.correct {
  background: #d8ffc4;
  border: 1px solid #60a03f;
}
#quizAns label.wrong {
  background: #ffe8e8;
  border: 1px solid #c78181;
} /* (X) DOES NOT MATTER - COSMETICS */
/* PAGE & BODY */
* {
  font-family: arial, sans-serif;
  box-sizing: border-box;
} body {
  display: flex;
  align-items: center; justify-content: center;
  min-height: 100vh;
  background-image: url(https://images.unsplash.com/photo-1554034483-04fda0d3507b?crop=entropy&cs=srgb&fm=jpg&ixid=MnwxNDU4OXwwfDF8cmFuZG9tfHx8fHx8fHx8MTY0ODAwMTA1MQ&ixlib=rb-1.2.1&q=85);
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  text-align: center;
} /* WIDGET */
.widget-wrap {
  width: 600px;
  padding: 30px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.4);
} /* FOOTER */
#code-boxx {
  font-weight: 600;
  margin-top: 30px;
}
#code-boxx a {
  display: inline-block;
  border: 0;
  padding: 5px;
  text-decoration: none;
  background: #b90a0a;
  color: #fff;
}</style>
<script type="text/javascript">var quiz = {
  // (A) PROPERTIES
  // (A1) QUESTIONS & ANSWERS
  // Q = QUESTION, O = OPTIONS, A = CORRECT ANSWER
  data: [
  {
    q : "What is the standard distance between the target and archer in Olympics?",
    o : [
      "50 meters",
      "70 meters",
      "100 meters",
      "120 meters"
    ],
    a : 1 // arrays start with 0, so answer is 70 meters
  },
  {
    q : "Which is the highest number on a standard roulette wheel?",
    o : [
      "22",
      "24",
      "32",
      "36"
    ],
    a : 3
  },
  {
    q : "How much wood could a woodchuck chuck if a woodchuck would chuck wood?",
    o : [
      "400 pounds",
      "550 pounds",
      "700 pounds",
      "750 pounds"
    ],
    a : 2
  },
  {
    q : "Which is the seventh planet from the sun?",
    o : [
      "Uranus",
      "Earth",
      "Pluto",
      "Mars"
    ],
    a : 0
  },
  {
    q : "Which is the largest ocean on Earth?",
    o : [
      "Atlantic Ocean",
      "Indian Ocean",
      "Arctic Ocean",
      "Pacific Ocean"
    ],
    a : 3
  }
  ],   // (A2) HTML ELEMENTS
  hWrap: null, // HTML quiz container
  hQn: null, // HTML question wrapper
  hAns: null, // HTML answers wrapper   // (A3) GAME FLAGS
  now: 0, // current question
  score: 0, // current score   // (B) INIT QUIZ HTML
  init: () => {
    // (B1) WRAPPER
    quiz.hWrap = document.getElementById("quizWrap");     // (B2) QUESTIONS SECTION
    quiz.hQn = document.createElement("div");
    quiz.hQn.id = "quizQn";
    quiz.hWrap.appendChild(quiz.hQn);     // (B3) ANSWERS SECTION
    quiz.hAns = document.createElement("div");
    quiz.hAns.id = "quizAns";
    quiz.hWrap.appendChild(quiz.hAns);     // (B4) GO!
    quiz.draw();
  },   // (C) DRAW QUESTION
  draw: () => {
    // (C1) QUESTION
    quiz.hQn.innerHTML = quiz.data[quiz.now].q;     // (C2) OPTIONS
    quiz.hAns.innerHTML = "";
    for (let i in quiz.data[quiz.now].o) {
      let radio = document.createElement("input");
      radio.type = "radio";
      radio.name = "quiz";
      radio.id = "quizo" + i;
      quiz.hAns.appendChild(radio);
      let label = document.createElement("label");
      label.innerHTML = quiz.data[quiz.now].o[i];
      label.setAttribute("for", "quizo" + i);
      label.dataset.idx = i;
      label.addEventListener("click", () => { quiz.select(label); });
      quiz.hAns.appendChild(label);
    }
  },   // (D) OPTION SELECTED
  select: (option) => {
    // (D1) DETACH ALL ONCLICK
    let all = quiz.hAns.getElementsByTagName("label");
    for (let label of all) {
      label.removeEventListener("click", quiz.select);
    }     // (D2) CHECK IF CORRECT
    let correct = option.dataset.idx == quiz.data[quiz.now].a;
    if (correct) {
      quiz.score++;
      option.classList.add("correct");
    } else {
      option.classList.add("wrong");
    }     // (D3) NEXT QUESTION OR END GAME
    quiz.now++;
    setTimeout(() => {
      if (quiz.now < quiz.data.length) { quiz.draw(); }
      else {
        quiz.hQn.innerHTML = `You have answered ${quiz.score} of ${quiz.data.length} correctly.`;
        quiz.hAns.innerHTML = "";
      }
    }, 1000);
  },   // (E) RESTART QUIZ
  reset : () => {
    quiz.now = 0;
    quiz.score = 0;
    quiz.draw();
  }
};
window.addEventListener("load", quiz.init);
</script>

Note: Copy the above quiz code and paste it into your blogger or website page. 

For bloggers, you have to switch the HTML view from composing view to insert the code

All quiz Code Sources: Codepen

Conclusion:

If You have suggestions or queries about the above Javascript Multiple Choice Quiz Code . just comment below with your name and suggestion or queries . we are trying to solve it as soon as possible.

thank you

Post a Comment

0Comments
Post a Comment (0)