Guide 3.6: Real Projects

Add Prev/Next Navigation

Our UI currently renders the first question, but the user is stuck there! We need to wire up the "Previous" and "Next" buttons so the student can traverse through the array of 40 questions.

Event Listeners

3.6.1

Open app.js and add event listeners to the navigation buttons we created in the HTML. These buttons will increment or decrement our currentQuestionIndex global variable.

const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');

prevBtn.addEventListener('click', () => {
  if (currentQuestionIndex > 0) {
    currentQuestionIndex--;
    renderQuestion(currentQuestionIndex);
  }
});

nextBtn.addEventListener('click', () => {
  if (currentQuestionIndex < examQuestions.length - 1) {
    currentQuestionIndex++;
    renderQuestion(currentQuestionIndex);
  }
});

Managing Button States

3.6.2

Currently, if the user is on Question 1 (index 0), clicking "Previous" does nothing, but the button still looks clickable. We should disable the "Previous" button on the first question, and the "Next" button on the last question. Let's update our renderQuestion() function to handle this.

// Add this to the BOTTOM of your renderQuestion() function
function renderQuestion(index) {
  // ... existing code ...
  
  // Disable 'Previous' if we are on the first question
  prevBtn.disabled = (index === 0);
  
  // Disable 'Next' if we are on the last question
  nextBtn.disabled = (index === examQuestions.length - 1);
  
  // Optional: Change 'Next' button text on the last question
  if (index === examQuestions.length - 1) {
    nextBtn.textContent = 'Finish Exam';
  } else {
    nextBtn.textContent = 'Next';
  }
}

What about jumping around?

Next, we will add a grid of buttons so the user can jump straight to Question 35.

Next Guide: Number Navigation →
Avatar

How can we help?

We reply immediately

Hello! 👋 How can we help you today?