Jill Stemm
Jill Stemm

Reputation: 43

JavaScript quiz works all but showing the question explanations

Before I start explaining please understand I am relatively new to coding, so please don't rag on me to bad, lol.

I am building a quiz that is multiple choice all of the quiz is working except for the part that is supposed to show the question explanation when the next button is clicked. When I add the code to the output.push() it appears on the screen and loops through it but my buttons stop working. I am not sure why they stop working.

I also need a way to hide the question explanation until the user has clicked an answer. Any help would be appreciated, thanks in advance.

window.onload = function() {
(function() {
    // Functions
    function buildQuiz() {
      // variable to store the HTML output
      const output = [];

      // for each question...
      myQuestions.forEach(
        (currentQuestion, questionNumber) => {

          // variable to store the list of possible answers
          const answers = [];

          // and for each available answer...
          for (var letter in currentQuestion.answers) {

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

          // add this question and its answers to the output
          output.push(
            `<div class="slide">
            <div class="question"> ${currentQuestion.question} 
           </div>
            <div class="answers"> ${answers.join("")} </div>
          </div>`
          )
        );
        //  <div 
       
      class="explanationOne">${currentQuestion.explanation.correct} 
      </div>
        //   <div 
      class="explanationTwo">${currentQuestion.explanation.explain} 
       </div>
        //   <div 
       class="explanationOne">${currentQuestion.explanation.source} 
       </div>
        document.write(); document.write(output.push($ {
          currentQuestion.explanation.correct
        }));
      }
    );
    // finally combine our output list into one string of HTML and 
   put it on the page
    quizContainer.innerHTML = output.join('');
  }

  function showResults() {

    // gather answer containers from our quiz
    const answerContainers = 
    quizContainer.querySelectorAll('.answers');

    // keep track of user's answers
    let numCorrect = 0;

    // for each question...
    myQuestions.forEach((currentQuestion, questionNumber) => {

      // find selected answer
      const answerContainer = answerContainers[questionNumber];
      const selector = 
      `input[name=question${questionNumber}]:checked`;
      const userAnswer = (answerContainer.querySelector(selector) 
      || {}).value;

      // if answer is correct
      if (userAnswer === currentQuestion.correctAnswer) {
        // add to the number of correct answers
        numCorrect++;

        // color the answers green
        answerContainers[questionNumber].style.color = 
        'lightgreen';
      }
      // if answer is wrong or blank
      else {
        // color the answers red
        answerContainers[questionNumber].style.color = 'red';
      }
    });

    // show number of correct answers out of total
    resultsContainer.innerHTML = 'Your Score:' + ' ' + 
      `${numCorrect} out of 
      ${myQuestions.length}`;


     }
 
    function showSlide(n) {
    slides[currentSlide].classList.remove('active-slide');
    slides[n].classList.add('active-slide');
    currentSlide = n;
    if (currentSlide === 0) {
      previousButton.style.display = 'inline-block';
      nextButton.style.display = 'inline-block';
      submitButton.style.display = 'inline-block';
      document.getElementById("submit").disabled = true;
      document.getElementById("previous").disabled = true;
    } else {
      submitButton.style.display = 'inline-block';
      document.getElementById("submit").disabled = false;
      document.getElementById("previous").disabled = false;
    }
    if (currentSlide === slides.length - 1) {
      previousButton.style.display = 'inline-block';
      nextButton.style.display = 'none';
      submitButton.style.display = 'inline-block';
      document.getElementById("submit").disabled = false;


    } else {
      previousButton.style.display = 'inline-block';
      nextButton.style.display = 'inline-block';
      submitButton.style.display = 'none';

    }
  }

  function showNextSlide() {
    showSlide(currentSlide + 1);
  }

  function showPreviousSlide() {
    showSlide(currentSlide - 1);
  }

  function showExplanation() {

    var x = document.getElementById('explanations');
    if (x.style.display === 'none') {
      x.style.display = 'block';
    } else {
      x.style.display = 'none';
    }

  };

  // Variables
  const quizContainer = document.getElementById('quiz');
  const resultsContainer = document.getElementById('results');
  const explainQuestion = document.getElementById('explanation');
  const myQuestions = [{
      question: "What color is the sky",
      answers: {
        a: "blue",
        b: "green",
        c: "yellow",
        d: "orange"
      },
      explanation: {
        correct: "Correct answer: A. Yep the sky is blue",
        explain: "Everyone knows that.
        ",
        source: "Your brain"

      },
      correctAnswer: "a"
    },
    {
      question: "What time do you wake up in the morning?",
      answers: {
        a: "Noon",
        b: "6 AM - 8 AM",
        c: "9 AM - 11 AM",
        d: "After noon"
      },
      explanation: {
        correct: "Correct answer: B. The early bird gets the 
        worm.",
        explain: "If you get up early you more likely to be 
        successful. 
      ",
      source: "life experience!"

    },
    correctAnswer: "b"
  }, 
];

   // Kick things off
   buildQuiz();

// Pagination
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const submitButton = document.getElementById('submit');
const slides = document.querySelectorAll(".slide");
let currentSlide = 0;

// Show the first slide
showSlide(currentSlide);

// Event listeners

previousButton.addEventListener("click", showPreviousSlide);
nextButton.addEventListener("click", showNextSlide);
submitButton.addEventListener('click', showResults);
// nextButton.addEventListener("click", myQuestions.explanation.correct);
// nextButton.addEventListener("click", myQuestions.explanation.explain); 
// nextButton.addEventListener("click", myQuestions.explanation.source);
})();
}
<body>
  <!--    START OF QUIZ-->
  <div id="border" class="uk-align-center uk-width-1-2">
    <div class="quiz-body">
      <h1 class="h1-quiz">Test Your Knowledge</h1>
      <div class="quiz-container">
        <div id="quiz"></div>
      </div>


      <div id="buttonGroup" class="uk-width-1-1 uk-align-center">
        <button id="previous" class="uk-text-center">Previous </button>
        <button id="next" class="uk-text-center">Next </button>
        <button id="submit" class="uk-text-center">Submit </button>
      </div>

      <div class="explanationOne"> </div>
      <div class="explanationTwo"></div>
      <div class="explanationOne"></div>

      <div id="results" class="uk-text-center uk-text-large uk-text-bold uk-margin-small-top">
      </div>
      <div class="uk-text uk-text-small uk-text-center">If you click the previous button once the quiz is complete the questions you answered correctly turn green and the incorrect answers are red.</div>
    </div>
  </div>
  <!--END OF QUIZ-->
  <br/>

  <script src="code.js"></script>
</body>

Upvotes: 0

Views: 165

Answers (1)

prograk
prograk

Reputation: 579

just done the basic of showing explanations when clicked on label.

https://codesandbox.io/s/epic-poitras-ldyxk?file=/src/index.js

The code is too big to paste here. Attaching screenshot.

enter image description here

Upvotes: 2

Related Questions