Nibbler
Nibbler

Reputation: 334

javascript: onclick go to specific div

I'm trying to create a "diagram" with divs. If user click on next it will show the next div and so on (this is done), but the thing i'm trying to reach is, sometimes some divs will have a question with "yes" or "no" buttons, and those buttons will target to some specific div.

Ex: Div 1 - Are you ok ? Yes - Go to Div 2 | No - Go to Div 3.

Is there a way to make this dynamic ? All divs have an ID.

Here's the code i've got so far.

HTML

 <div id="main">   
  <h3 class="despistes">Some Title</h3>
      <div class="info" id="1" style="display:block">Div 1</div>
      <div class="info" id="2">Div 2</div>
      <div class="info" id="3">Div 3</div>
      <div class="info" id="4">Div 4</div>
      <div class="info" id="5">Div 5</div>
      <div class="info" id="6">Div 6</div>
      <div class="info" id="7">Div 7</div>
      <div class="info" id="8">Div 8</div>

 <button class="button" onclick="mostraDiv('inicio')" style="float:left">inicio</button>
 <button class="button" onclick="mostraDiv('avancar')" style="float:right">seguinte</button>
 <button class="button" onclick="mostraDiv('anterior')" style="float:right">retroceder</button>

</div>

JS

var divNo = 0;
function mostraDiv(direction) {
  var sel = document.getElementById('main').getElementsByTagName('div');
  for (var i=0; i<sel.length; i++) { sel[i].style.display = 'none'; }
  switch (direction) {
    case 'inicio' : divNo = 0; break;
    case 'anterior' : divNo--;   break;
    case 'avancar' : divNo++;   break;
    case 'ultima' : divNo = sel.length-1; break;

  }
  if (divNo > sel.length-1) { divNo = 0; }
  else { if (divNo < 0) { divNo = sel.length-1; } }
  sel[divNo].style.display = 'block';
}

onload = function() {
  mostraDiv('s');
};

This function i found here and works fine for me.

Thanks in Advance.

Upvotes: 0

Views: 4445

Answers (1)

Martial
Martial

Reputation: 1562

try this :

<p>Are You OK ?</p>
<button class="button" onclick="goToDiv(2)" style="float:left">Yes</button>
<button class="button" onclick="goToDiv(3)" style="float:left">No</button>

function goToDiv(divNo) {
  var sel = document.getElementById('main').getElementsByTagName('div');
  for (var i=0; i<sel.length; i++) { sel[i].style.display = 'none'; }
  if (divNo > sel.length-1) { divNo = 0; }
  else { if (divNo < 0) { divNo = sel.length-1; } }
  sel[divNo].style.display = 'block';
}

Upvotes: 1

Related Questions