Simon Game addEventListener doubt

I have the following code that works fine, but has a logic problem. I have two buttons, the onOff, which is a checkbox, and the startButton. When I press the onOff button, and it gets checked, the turnedOn class is added, then I press the onOff button again, and the class is removed. My problem is, even though i never pressed the startButton, events are added to it. Why does that work this way? In my head at least the part in italic would run only if I press the startButton.


function randomNumber() {
  return Math.floor(Math.random() * 4);
};

window.onload = function () {
  var onOff = document.querySelector('input');
  var timer = document.querySelector('.startStrictDiv span');
  var startButton = document.querySelector('#start');
  onOff.checked = false;
  **onOff**.addEventListener('click', function () {
    if (this.checked == true) {
      timer.classList.add('turnedOn');
      **startButton**.addEventListener('click', function () {
        _timer.classList.remove('turnedOn');_
      _timer.classList.add('blink');_
      })
    } else {
      timer.classList.remove('turnedOn');
      timer.classList.remove('blink');
    }
  })
}

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

Thanks Ariel! My second post…