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.1Open 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.2Currently, 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';
}
}