Just starting out with Javascript, I'm currently developing a quiz solution that utilizes divs and buttons to navigate through the questions. I've written some JavaScript code for this functionality but I'm encountering an issue where it doesn't progress to the final question as expected. Any assistance on why the next button doesn't lead to the last question would be greatly appreciated.
var question = document.querySelectorAll('.question');
var next = document.getElementById("next");
next.addEventListener("click", function() {
var question = document.querySelectorAll(".question");
for (var i = 0; i < question.length; i++) {
if (question[i].style.display != "none") {
question[i].style.display = "none";
//restores original questions
if (i == question.length - 1) {
question[0].style.display = "block";
} else {
question[i + 1].style.display = "block";
}
break;
}
}
});
.question {
margin: 50px;
width: 300px;
height: 300px;
border-radius: 10px;
padding: 50px;
text-align: center;
color: white;
background: #333;
position: relative;
display: none;
}
.visible {
display: block;
}
.q-input,
.move {
margin: 10px;
border: none;
padding: 10px;
}
.move {
display: flex;
justify-content: space-between;
}
.move button {
padding: 5px;
font-size: 16px;
width: 60px;
border-radius: 5px;
border: none;
cursor: pointer;
transition: 0.4s;
}
.move button:hover {
box-shadow: -2px -2px 20px #fff;
}
.move button:focus {
outline: none;
}
<div class="question visible">
<h1>Question <span class="one">1</span></h1>
<p>What is your Name</p>
<input type='text' class="q-input">
<div class="move">
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>
</div>
<div class="question">
<h1>Question 2</h1>
<p>What is your Age</p>
<input type="text" class="q-input">
<div class="move">
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>
</div>
<div class="question">
<h1>Question 3</h1>
<p>What is your Sex</p>
<input type="text" class="q-input">
<div class="move">
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>
</div>