girish girish - 29 days ago 23
Javascript Question

Toggle multiple divs one at a time with 1 button using Jquery

I have four divs which i want to toggle one at a time with a single button. I want to toggle them one after the other and not randomly. I have tried something like below.



$(document).ready(function() {
$('#toggle').click(function() {
$('#1').hide();
});
$('#toggle').click(function() {
$('#2').hide();
});
$('#toggle').click(function() {
$('#3').hide();
});
$('#toggle').click(function() {
$('#4').hide();
});
});

.divs {
border: 1px solid;
height: 30px;
}

<div id='1' class='divs'></div>
<div id='2' class='divs'></div>
<div id='3' class='divs'></div>
<div id='4' class='divs'></div>

<button id='toggle'>
toggle
</button>




Answer

Save the state on each click.

$(document).ready(function() {

  var state = 1;
  $('#toggle').click(function() {

    if(state==1){
       $('#1').hide();
       state=2;
    } 
    else if(state==2){
       $('#2').hide();
       state=3;
    }
    else if(state==3){
       $('#3').hide();
       state=4;
    }
    else if(state==4){
       $('#4').hide();
       state=1; //back to state
    }
  });