Reputation: 19
script code when user clicks button the 1st div (#1-div) shows and when they click again 2nd div (#2-div) shows...etc
Here is what I worked on so far:
'''
<head>
<style>
#div-1, #div-2, #div-3{
display: none;
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<form>
<input type="text" id="number" value="0"/>
</form>
<p>What is the color of the ocean?</p>
<div id="div-1">
<p>What is the color of the sky?</p>
</div>
<div id="div-2">
<p>What is the color of the sand?</p>
</div>
<div id="div-3">
<p>What is the color of the bus?</p>
</div>
<button onclick="nextQuestion()">Next Question</button>
<script>
function nextQuestion()
{
}
</script>
'''
Upvotes: 0
Views: 143
Reputation: 1335
Remember the index of current shown element, and increase it by +1 after each click:
let question = document.querySelectorAll(".question");
let index = 0;
show(question[index]);
document.getElementById("next").addEventListener("click", function _tmp() {
hide(question[index]);
index++;
if( !question[index] ) {
this.removeEventListener("click", _tmp);
this.textContent = "No more questions!";
// this keyword refers to context of function call (here: The clicked button)
return;
}
show(question[index]);
});
/***/
function show(el, value) {
el.style.display = value || "block";
}
function hide(el) {
el.style.display = "none";
}
.question {
display: none;
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<button id="next">Next Question</button>
<hr>
<div class="question">
<p>What is the color of the ocean?</p>
</div>
<div class="question">
<p>What is the color of the sky?</p>
</div>
<div class="question">
<p>What is the color of the sand?</p>
</div>
<div class="question">
<p>What is the color of the bus?</p>
</div>
P.s. If numbered ids, class names, variables, etc. appear in your code, that means, something went wrong) Try to solve the problem in more general way, with loops, arrays.
Upvotes: 4