Mini Quiz Game Issue using fetch, click listener, and functions

I have been trying to solve my issue for a while now, but have had no luck. My issue is that once I click to start game and then answer the first question I am then lead to the second question (as expected and as I wanted). After picking out an answer for the second question, the recursive function gets called again (as expected) which should bring me to the third question like it did with the second question, but instead it begins to skip questions and level++ adds on its own without clicking. I feel like its a double recursive problem, but I dont see the logic on how when it didn’t make a mistake after answering the first question.

Note: this is more a cry for help vs trying to walk me through solving it myself. I have been at this for two weeks on and off.

JS

// VARIABLE LIBRARY 
var timeLimitEl = document.querySelector('#time-limit')
var startGameEl = document.querySelector('.start-game')
var startButtonEl = document.querySelector('#start-button')
var questionTitle = document.querySelector('#question-title')
var questionBox = document.querySelector('.question-box')
var optionBox = document.querySelector('#option-box')
var option1 = document.querySelector('#option1')
var option2 = document.querySelector('#option2')
var option3 = document.querySelector('#option3')
var option4 = document.querySelector('#option4')
var timeLeft = 120
var score = timeLeft
var level = 0


// // TIMER
// const timer = () => {
//   setInterval(() => {
//     timeLeft--
//     timeLimitEl.textContent = timeLeft
//     console.log(timeLeft)
//   }, 1000)
// }

// START BUTTON
startButtonEl.addEventListener('click', () => {
  startGameEl.style.display = "none"
  // timer()
  fetchedData()
})

// FETCHED DATA & THE GAME (second try)
let fetchedData = () => {
  fetch('data.json')
  .then((res) => res.json())
  .then((data) => {
    theGame()
    // THE GAME (retry) - same issue as original 
    function theGame() {
      console.log("current level: ", level);
      console.log("");
      questionBox.style.display = "block"
      questionTitle.textContent = data[level].question
      option1.textContent = data[level].choice1
      console.log('data[level].choice1: ', data[level].choice1);
      option2.textContent = data[level].choice2 
      console.log('data[level].choice2: ', data[level].choice2);
      option3.textContent = data[level].choice3
      console.log('data[level].choice3: ', data[level].choice3);
      option4.textContent = data[level].choice4
      console.log('data[level].choice4: ', data[level].choice4);
      console.log("");

      optionBox.addEventListener('click', (event) => {
        
        if (event.target.textContent !== data[level].answer.toString()) {  
          console.log("event.target", event.target)
          console.log("wrong");
          level++
          console.log("level if wrong: ", level);
          // AFTER ISSUE IS FIXED: decrease seconds from time
        } else if (event.target.textContent === data[level].answer.toString()) {
          console.log("correct!");
          level++
          console.log("level if correct: ", level);
          // AFTER ISSUE IS FIXED:  add seconds to time
        }
        theGame()
      })
    }
  })
}

JSON (data.json)

[
  {
    "question" : "What does 2 + 2 equal?",
    "choice1" : 7,
    "choice2" : 23,
    "choice3" : 67,
    "choice4" : 4,
    "answer" : 4
  },
  {
    "question" : "What does 12 + 2 equal?",
    "choice1" : 1,
    "choice2" : 14,
    "choice3" : 141,
    "choice4" : 4,
    "answer" : 14
  },
  {
    "question" : "What does 1 + 20 equal?",
    "choice1" : 21,
    "choice2" : 29,
    "choice3" : 66,
    "choice4" : 3,
    "answer" : 21
  },
  {
    "question" : "What does 6 + 2 equal?",
    "choice1" : 8,
    "choice2" : 23,
    "choice3" : 40,
    "choice4" : 25,
    "answer" : 8
  },
  {
    "question" : "What does 3 + 2 equal?",
    "choice1" : 753,
    "choice2" : 5,
    "choice3" : 35,
    "choice4" : "Not this one. I am here for you ;)",
    "answer" : 5
  }
]

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>

  <header>
    <h6>View High Scores</h6>
    <h6>Time: <span id="time-limit">120</span></h6>
  </header>

  <div class="start-game">
    <h1>Quiz Game</h1>
    <p>(click button to begin game)</p>
    <button id="start-button">Start</button>
  </div>

  <div>
    <h3 id="question-title"></h3>
    <div class="question-box">
      <div class="first-question">
        <ol id="option-box">
          <li class="option1" id="option1"></li>
          <li class="option2" id="option2"></li>
          <li class="option3" id="option3"></li>
          <li class="option4" id="option4"></li>
        </ol>
      </div>
    </div>
  </div>

  <div id="high-scores">

  </div>



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

CSS

.start-game {
  display: block;
}

li:hover {
  cursor: pointer;
}

.question-box {
  display: none;
}

1 Like

Sorry, I re-edited to show fetchedData being called (all of the JS is now shown in issue)

if i put the event listener inside of a function would that work? or would the event listener just to be completely outside of the entire fetchedData function scope?

1 Like

Ok, I will try that thanks Randell. And thank you for the explanation. That makes total sense on how it is creating more and more event listeners.

1 Like

I was able to rearrange your code a little to get it working as you are wanting. I did not have to create any additional code. I only moved the event listener part.

1 Like

I got it, thank you :slight_smile:

At first I put outside completely in the global scope but then data wasnt defined, but then realized it can go back in the fetch scope where data was being used as long its not in the function scope. Super helpful, thank you again.

1 Like

It was just for practice. I know its not the most robust. I was helping a student in bootcamp with his issue and I figured i would write it the same way. It was the same day the class was learning fetches as well.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.