Home > Mobile >  When building a quiz app in Javascript how can I one question to the next?
When building a quiz app in Javascript how can I one question to the next?

Time:07-04

I am currently in the process of building a quiz app and one of the things I am trying to accomplish is going from one question to the next by clicking the "next" button I have created. I have 3 questions created and I can only get my quiz to go from question 1 to question three. So essentially question 2 is skipped and I am not sure why. Any help would be appreciated! Please see my code/code pen below https://codepen.io/Michaelm4100/pen/GRQxNQO?editors=1011

// activeQuestion function to remove / add the active-question to each question 
function activeQuestion(el) {
   var que = document.getElementsByClassName('question');

    for (var questions of que) {
      // console.log(questions)
      
      // removing active-question class 
      questions.classList.remove('active-question');
    }
    questions.classList.add('active-question');
}


var nextButton = document.getElementsByClassName('nxt-btn'); 


for (var buttons of nextButton) 
  
  buttons.addEventListener('click', function(e){
    // calling active Question to button event listener 
    activeQuestion(e);
  })
}

CodePudding user response:

When you do var questions of que, the final value of questions is the last element - so when you do questions.classList.add('active-question') after the loop is finished, you're always adding the class to the final element.

Instead, keep track of the current active question with a persistent index variable.

const questions = document.querySelectorAll('.question');
let activeQuestionIndex = 0;
for (const nextButton of document.getElementsByClassName('nxt-btn')) {
    nextButton.addEventListener('click', () => {
        questions[activeQuestionIndex].classList.remove('active-question');
        activeQuestionIndex  ;
        questions[activeQuestionIndex]?.classList.add('active-question');
    });
}
  • Related