vendredi 9 février 2018

Display javascript quiz after clicking button

I would like to display this quiz after a button is clicked (onclick). At this moment it appears directly into the website. I am sure is pretty simple but I am stuck here. Do you know how should I add the button code?

Here the HTML:

  <div id="quiz"></div>

Here the JavaScript quiz:

(function() {
function buildQuiz() {
  const output = [];

  myQuestions.forEach((currentQuestion, questionNumber) => {
    const answers = [];

    for (letter in currentQuestion.answers) {
      answers.push(
        `<label>
        <input type="radio" name="question${questionNumber}" value="${letter}">
        ${letter} :
        ${currentQuestion.answers[letter]}
      </label>`
      );
    }

    output.push(
      `<div class="question"> ${currentQuestion.question} </div>
    <div class="answers"> ${answers.join("")} </div>`
    );
  });

  quizContainer.innerHTML = output.join("");
}


const quizContainer = document.getElementById("quiz");
const myQuestions = [{
    question: "Who is the strongest?",
    answers: {
      a: "Superman",
      b: "The Terminator",
      c: "Waluigi, obviously"
    },
    correctAnswer: "c"
  },
  {
    question: "What is the best site ever created?",
    answers: {
      a: "SitePoint",
      b: "Simple Steps Code",
      c: "Trick question; they're both the best"
    },
    correctAnswer: "c"
  }
];




Aucun commentaire:

Enregistrer un commentaire