HereToLearn HereToLearn - 5 months ago 8
HTML Question

Showing and hiding div tags by their ID order using a button

I made a small questionnaire and I placed each question in a div tag. I'm trying to display the div tags in order, so when the user click the "Next" button it will move on to the next div and hide the previous one. Kind of like a paging system? I thought about creating some sort of a for loop but I feel like my code is super messy. Any suggestions? Thanks in advance.

<form>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>
<div id="6"></div>
<div id="7"></div>
<div id="8"></div>
<div id="9"></div>
<div id="10"></div>



<button type="button">Next</button>
<button type="button">Back</button>
</form>

<script>
visible(){
document.getElementById('1').style.display = "block";
document.getElementById('2').style.display = "none";
document.getElementById('3').style.display = "none";
document.getElementById('4').style.display = "none";
document.getElementById('5').style.display = "none";
document.getElementById('6').style.display = "none";
document.getElementById('7').style.display = "none";
document.getElementById('8').style.display = "none";
document.getElementById('9').style.display = "none";
document.getElementById('10').style.display = "none";
}



Jem Jem
Answer

You can use javascript functions to setup your divs. This uses jQuery for smooth transition as well.

<div id="1">Question 1</div>
<div id="2" class="hidden">Question 2</div>
<div id="3" class="hidden">Question 3</div>
<div id="4" class="hidden">Question 4</div>
<div id="5" class="hidden">Question 5</div>
<div id="6" class="hidden">Question 6</div>
<div id="7" class="hidden">Question 7</div>
<div id="8" class="hidden">Question 8</div>
<div id="9" class="hidden">Question 9</div>
<div id="10" class="hidden">Question 10</div>


<button type="button" onclick="reverseDiv();">Back</button>
<button type="button" onclick="advanceDiv();">Next</button> 

<script>
var divNum=1;

advanceDiv = function() {
    if(divNum < 10) {
        divNum++;
        $('#' + (divNum-1)).slideToggle();
        $('#' + divNum).slideToggle();
    }
    else {
        /* last slide reached */
    alert('last question');
    }
}

reverseDiv = function() {
  if(divNum > 1) {
        divNum--;
        $('#' + (divNum+1)).slideToggle();
        $('#' + divNum).slideToggle();
    }
  else {
    alert('first question');
  }
}
</script>

Here's a jsfiddle to show functionality (and also includes arrow keys to move between functions): https://jsfiddle.net/79xupebb/1/

Comments