Quiz app in JavaScript example

by danielkwood

HTML

<html>
<head>
    <title>Quiz</title>
    <link rel="stylesheet" href="style.css">
    <script src="quiz.js"></script>
</head>

<body>
    <h2 id="quiz_status"></h2>
    <div id="quiz"></div>
</body>

</html>

CSS

body{
    font-family: Arial;
    min-height: 500px;
}
div#quiz{
    border: #5AB029 3px solid;
    padding: 10px 40px 40px 40px;
    background-color: #E5FCE3;
    width: 50%;
}

JavaScript

// pos is position of where the user is up to in the quiz (which question they're up to)
var pos = 0, quiz, quiz_status, question, selectedAnswer, options, optionA, optionB, optionC, correct = 0;

// this is a multi-dimensional array with objects containing each question
var questions = [
  {
      question: "What is 36 + 42",
      a: "64",
      b: "78",
      c: "76",
      answer: "B"
    },
  {
      question: "What is 7 x 4?",
      a: "21",
      b: "27",
      c: "28",
      answer: "C"
    },
  {
      question: "What is 16 / 4?",
      a: "4",
      b: "6",
      c: "3",
      answer: "A"
    },
  {
      question: "What is 8 x 12?",
      a: "88",
      b: "112",
      c: "96",
      answer: "C"
    },
  ];

// this get function is short for the getElementById function	
function get(x){
  return document.getElementById(x);
}

// this function renders a question for display on the page
function renderQuestion(){
  quiz = get("quiz");
  if(pos >= questions.length){
    quiz.innerHTML = "<h2>You answered "+correct+" of "+questions.length+" questions correctly.</h2><br><button onclick='renderQuestion()'>Play again</button>";
    get("quiz_status").innerHTML = "Quiz completed";
    // resets the variable to allow users to restart the quiz
    pos = 0;
    correct = 0;
    // stops rest of renderQuestion function running when quiz is completed
    return false;
  }

  get("quiz_status").innerHTML = "Question "+(pos+1)+" of "+questions.length;
  
  question = questions[pos].question;
  optionA = questions[pos].a;
  optionB = questions[pos].b;
  optionC = questions[pos].c;

  // display the current question
  quiz.innerHTML = "<h3>"+question+"</h3>";

  // display the answer options
  // the += appends to the data we started on the line above
  quiz.innerHTML += "<label> <input type='radio' name='options' value='A'> "+optionA+"</label><br>";
  quiz.innerHTML += "<label> <input type='radio' name='options' value='B'> "+optionB+"</label><br>";
  quiz.innerHTML +=...