JavaScript Quiz Template


/ Published in: JavaScript
Save to your folder(s)

**Simple JavaScript Quiz**

Edit the main quiz array with your own questions, then publish. Since it's an entire HTML file, it's best to save this file on a server and embed it as needed using an iframe tag.


Copy this code and paste it in your HTML
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>Quiz</title>
  6. <!-- Quiz Written By Jeremy Rue, UC Berkeley Graduate School of Journalism -->
  7. <style>
  8. /*css reset */
  9. html,body,div,span,h1,h2,h3,h4,h5,h6,p,code,small,strike,strong,sub,sup,b,u,i{border:0;font-size:100%;font:inherit;vertical-align:baseline;margin:0;padding:0;}
  10. article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section{display:block;}
  11. body{line-height:1; font:normal 0.9em/1em "Helvetica Neue", Helvetica, Arial, sans-serif;}
  12. ol,ul{list-style:none;}
  13. #frame{max-width:620px;width:100%;border:1px solid #ccc;background:#eee;padding:10px;}
  14. #content{font:normal normal 1em/1.5em "Helvetica Neue", Helvetica, Arial, sans-serif;margin:0 40px 10px;}
  15. h1{font:normal bold 2em/1.8em "Helvetica Neue", Helvetica, Arial, sans-serif;text-align:left;background:#ccc;padding:0 15px;width:auto}
  16. h2{font:italic bold 1.3em/1.2em "Helvetica Neue", Helvetica, Arial, sans-serif;padding:5px 15px 15px;}
  17. input[type=radio]{margin:0 10px 5px -22px;} label{margin:0 0 5px;}
  18. #score p{font-size:0.95em; font-style:italic; color:#666; float:right;margin:5px 5px 0 0;}
  19. #score:after{content:".";display:block;clear:both;visibility:hidden;line-height:0;height:0;}
  20. #response{min-height:70px; margin:10px; }
  21. #response h3{font:normal bold 1.2em/1.5em "Helvetica Neue", Helvetica, Arial, sans-serif; margin:5px 0;}
  22. </style>
  23. <script>
  24.  
  25. var quiz = [
  26. {
  27. "question" : "Q1: Who came up with theory of relativity?",
  28. "choices" : [
  29. "Sir Isaac Newton",
  30. "Nicolaus Copernicus",
  31. "Albert Einstein",
  32. "Ralph Waldo Emmerson"
  33. ],
  34. "correct" : "Albert Einstein",
  35. "explanation" : "Albert Einstein drafted the special theory of relativity in 1905.",
  36.  
  37. },
  38. {
  39. "question" : "Q2: Who is on the two dollar bill?",
  40. "choices" : [
  41. "Thomas Jefferson",
  42. "Dwight D. Eisenhower",
  43. "Benjamin Franklin",
  44. "Abraham Lincoln"
  45. ],
  46. "correct" : "Thomas Jefferson",
  47. "explanation" : "The two dollar bill is seldom seen in circulation. As a result, some businesses are confused when presented with the note.",
  48. },
  49. {
  50. "question" : "Q3: What event began on April 12, 1861?",
  51. "choices" : [
  52. "First manned flight",
  53. "California became a state",
  54. "American Civil War began",
  55. "Declaration of Independence"
  56. ],
  57. "correct" : "American Civil War began",
  58. "explanation" : "South Carolina came under attack when Confederate soldiers attacked Fort Sumter. The war lasted until April 9th 1865.",
  59. },
  60.  
  61. ];
  62.  
  63. var currentQuestion = 0;
  64. var score = 0;
  65. var askingQuestion = true;
  66.  
  67. function loadQuestion(){
  68.  
  69. //set temporary variable for creating radio buttons
  70. var radioButton;
  71.  
  72. //clear out radio buttons from previous question
  73. document.getElementById('content').innerHTML = "";
  74.  
  75. //loop through choices, and create radio buttons
  76. for(var i=0; i < quiz[currentQuestion]["choices"].length; i++){
  77.  
  78. radioButton = document.createElement('input');
  79. radioButton.type = 'radio';
  80. radioButton.name = 'quiz';
  81. radioButton.id = 'choice'+ (i+1);
  82. radioButton.value = quiz[currentQuestion]["choices"][i];
  83.  
  84. //create label tag, which hold the actual text of the choices
  85. var label = document.createElement('label');
  86. label.setAttribute('for','choice'+ (i+1));
  87. label.innerHTML = quiz[currentQuestion]["choices"][i];
  88.  
  89. //create a <br> tag to separate options
  90. var br = document.createElement('br');
  91.  
  92. //attach them to content. Attach br tag, then label, then radio button
  93. document.getElementById('content').insertBefore(br);
  94. document.getElementById('content').insertBefore(label, br);
  95. document.getElementById('content').insertBefore(radioButton, label);
  96. }
  97.  
  98. //load the question
  99. document.getElementById('question').innerHTML = quiz[currentQuestion]["question"];
  100.  
  101. //setup score for first time
  102. if(currentQuestion == 0){
  103. document.getElementById('score').innerHTML = '<p>score: 0 right answers out of ' + quiz.length +' possible</p>';
  104. }
  105. }
  106.  
  107. function checkAnswer(){
  108.  
  109. //are we asking a question, or proceeding to next question?
  110. if(askingQuestion){
  111.  
  112. //change button text to next question, so next time they click it, it goes to next question
  113. document.getElementById('check').innerHTML = 'Next Question';
  114. askingQuestion = false;
  115.  
  116. //determine which radio button they clicked
  117. var userpick;
  118. var correctIndex;
  119. var radios = document.getElementsByName('quiz');
  120. for(var i=0; i < radios.length; i++){
  121. if(radios[i].checked){ //if this radio button is checked
  122. userpick = radios[i].value;
  123. }
  124. //get index of correct answer
  125. if(radios[i].value == quiz[currentQuestion]["correct"]){
  126. correctIndex = i;
  127. }
  128. }
  129.  
  130. //set the color if they got it right, or wrong
  131. if(userpick == quiz[currentQuestion]["correct"]){
  132. score++;
  133. document.getElementsByTagName('label')[correctIndex].style.color = "green";
  134. document.getElementsByTagName('label')[correctIndex].style.fontWeight = "bold";
  135. document.getElementById('explanation').innerHTML = "<h3>Correct!</h3>";
  136. } else {
  137. document.getElementsByTagName('label')[correctIndex].style.color = "red";
  138. document.getElementsByTagName('label')[correctIndex].style.fontWeight = "bold";
  139. document.getElementById('explanation').innerHTML = "<h3>Incorrect</h3>";
  140. }
  141.  
  142. document.getElementById('explanation').innerHTML += '<p>' + quiz[currentQuestion]["explanation"] + '</p>';
  143. document.getElementById('score').innerHTML = '<p>score: '+ score +' right answers out of ' + quiz.length +' possible</p>';
  144.  
  145.  
  146. } else { //reset form and move to next question
  147.  
  148. //setting up so user can ask a question
  149. askingQuestion = true;
  150.  
  151. //change button text back to 'submit answer'
  152. document.getElementById('check').innerHTML = 'Submit Answer';
  153.  
  154. document.getElementById('explanation').innerHTML = "";
  155.  
  156. //if we're not on last question, increase question number
  157. if(currentQuestion < quiz.length - 1){
  158. currentQuestion++;
  159. loadQuestion();
  160. } else {
  161. showFinalResults();
  162. }
  163.  
  164. }
  165. }
  166.  
  167. function showFinalResults(){
  168.  
  169. document.getElementById('content').innerHTML = '<h2>You Completed The Quiz</h2>';
  170. document.getElementById('content').innerHTML += '<p>Below are your results:</p>';
  171. document.getElementById('content').innerHTML += '<h2>' + score + ' out of ' + quiz.length + ' questions, ' + Math.round(score/quiz.length * 100) + '%</h2>';
  172.  
  173. //delete the button
  174. var button = document.getElementById('check');
  175. button.parentNode.removeChild(button); //js requires you to delete elements from the parent
  176.  
  177. //remove question
  178. document.getElementById('question').innerHTML = "";
  179.  
  180. }
  181.  
  182.  
  183. window.onload = loadQuestion;
  184.  
  185. </script>
  186.  
  187. </head>
  188. <body>
  189. <div id="frame">
  190. <h1>Quiz Title Here</h1>
  191. <div id="score"><p>score: 0 right answers out of 0 possible</p></div>
  192. <h2 id="question">Question here</h2>
  193. <div id="content">
  194.  
  195. </div>
  196. <button id="check" onclick="checkAnswer()">Submit Answer</button>
  197. <div id="response">
  198. <div id="explanation"></div>
  199. </div>
  200. </div>
  201. </body>
  202. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.