Cannot set property

I’m trying to figure out why I can’t get my code to subtract time from the countdown when wrong answers are clicked, this is my current HTML and snippet from the js. It works fine until I test a wrong answer and then the timer stops and I get "Cannot set property ‘textContent’ of null. I’ve included all of the code if that helps, I’m still very new at this and mostly going off random knowledge and advice.

var time = 80;
var TimerEl = document.getElementById('time');
var timerId;
var questionNum;

var questions = [{
    question: "What is 2+2",
    answers: ["1", "3", "4"],
    correct: "4"
  },

  {
    question: "What is 8+8",
    answers: ["32", "12", "16"],
    correct: "16"
  },

  {
    question: "What is 4+4",
    answers: ["8", "24", "17"],
    correct: "8"
  },

]

function startQuiz(event) {
  event.preventDefault();
  questionNum = 0
  document.querySelector('#startQuiz')
  timerId = setInterval(clockTick, 1000);
  startBtn.style.display = 'none'
  showQuestion();
}

function showQuestion() {
  var question = questions[questionNum]
  var questionEl = document.querySelector('#questionBox')
  questionEl.innerHTML = `
                <div class="alert alert-warning"><h3>${question.question}</h3>
                 `
  for (var i = 0; i < question.answers.length; i++) {
    var answer = question.answers[i]
    questionEl.innerHTML += `
                <button onClick="selectAnswer(event,'${answer}')" class="btn btn-secondary btn-block">${answer}</button>
                `
  }
}

function selectAnswer(event, answer) {
  event.preventDefault()
  if (answer === questions[questionNum].correct) {
    console.log(`Yay you got it!`)
  } else {
    console.log(`WRONG -10 seconds`)
    timerDecrease(10)
  }
  questionNum++
  if (questionNum < questions.length)
    showQuestion()
  else
    endQuiz()
}

function clockTick() {
  time--;
  timerEl.textContent = time;
  if (time <= 0) {
    endQuiz();
  }
}

function timerDecrease(byValue = 1) {
  timerEl -= byValue
  document.getElementByID('timerEl').textContent = timerEl
  if (timerEl < 1)
    endQuiz()
}


function endQuiz() {
  if (event) event.preventDefault();
  console.log(`Quiz complete`);
  clearInterval(timerId);
  document.getElementById('startBtn').style.display = 'inline';
}
<div class="container">
  <h1>Quiz</h1>
  <div class="alert alert-light">
    <button id="startBtn" onClick="startQuiz(event)" class="float-end">Start Quiz</button>
    <h2>Timer:</h2>
    <div id="timerEl">
      <p id="clockTick"></p>
    </div>
  </div>
  <div id='quizPage' class="card">
    <form id="questionBox" class="card-body">
    </form>
    <div id='answerResponse' class="card-footer alert-secondary">
      Choose the correct answer
    </div>
  </div>
  <!-- <div id='finalScore' class="card d-none">
    Final Score
  </div> -->
</div>

82 thoughts on “Cannot set property”

Leave a Comment