Add function to EventListener & Keep arguments, Avoid Function Running Multiple Times

I am stuck and I can’t figure out how to fix my code.

This is my code:

    const updateScore = (isCorrect) => {
    // Update Game Variables
    if (isCorrect === true) {
      counter++
      score += 100;
    }
  }

  // Reset Styling
  const resetLoadedQuestionStyling = (isCorrect) => {
    questionScreen.style.display = 'none';
    answerArr.forEach(answer => {
      answer.classList.remove('correct');
      answer.classList.remove('wrong');
      answer.classList.remove('disable');

      updateScore(isCorrect)
    });
  }

  const styleAnswer = (div, isCorrect) => {
    if (isCorrect === true) {
      div.classList.add('correct');
    } else {
      div.classList.add('wrong');
      for (let i = 0; i < answerArr.length; i++) {
        if (i === currentQuestion.correct) {
          answerArr[i].classList.add('correct');
        }
      }
    }

    // Prevent Second Check
    answerArr.forEach(answer => {
      answer.classList.add('disable');
    });

    // Reset Styling
    setTimeout(() => {
      resetLoadedQuestionStyling(isCorrect);
    }, 3000);
  }

  const checkAnswer = (div, index) => {
    const userChoice = index;
    // Default Answer State
    let isCorrect = false;
    if (userChoice === currentQuestion.correct) {
      isCorrect = true;
    }
    styleAnswer(div, isCorrect);
  }

  answerArr.forEach((div, index) => {
    div.addEventListener('click', () => {
      checkAnswer(div, index);
    });
  });

I have an array, that consists of 4 divs. (answerArr).

I am comparing the index of the divs with my (currentQuestion.correct), which is stored in another array of objects.

Everything good so far. The problem occurs, when I update my counter and my score.

And I know exactly why:

answerArr.forEach((div, index) => {
    div.addEventListener('click', () => {
      checkAnswer(div, index);
    });
  });

This is running my checkAnswer function four times.. so my score gets increased four times, instead of one. (Example: counter = 4, score = 400 after one run.)

An easy fix to this is to remove the function invoked in the event listener and place it directly in it.

Example:

answerArr.forEach((div, index) => {
    div.addEventListener('click', checkAnswer);
  });

But than I can’t pass my arguments (div and index) in order to properly move to the other functions.

Can you come up with a solution and help me.

Thank You all in advance!

53 thoughts on “Add function to EventListener & Keep arguments, Avoid Function Running Multiple Times”

Leave a Comment