Milind Pandharkame Milind Pandharkame - 4 months ago 11
Javascript Question

How to repeatedly loop through divs

I have a script which changes the div display property on click on Next or Previous buttons. I am able to click on Next and see the next div or click on Previous to see the previous one; however, once it reaches to the end the classList becomes undefined or null. What I want to do is, when the page is loaded for the firs time, I want the user to click on Next until the end and then to the first div like in a loop. Also, if the user clicks on Previous from the first page, then I would want the user to see the last div. Any help is appreciated. Thanks! Below is the code..



var yogNumber = 0;
var yogs = document.querySelectorAll('.yog');

function next() {
yogNumber++;
if (yogs.length > yogNumber) {
document.querySelector('.active').classList.remove('active');
yogs[yogNumber].classList.add('active');
}

}

function previous() {
yogNumber--;
if (yogs.length > yogNumber) {
document.querySelector('.active').classList.remove('active');
yogs[yogNumber].classList.add('active');
}

}

.yog {
display: none
}
.active {
display: block
}

<div class="yog active">
<div id="heading">Text 1</div>
</div>

<div class="yog">
<div id="heading">Text 2</div>
</div>

<div class="yog">
<div id="heading">Text 3</div>
</div>

<div class="yog">
<div id="heading">Text 4</div>
</div>
<br />
<div id="left" onclick="previous()">
<</div>
<br />
<div id="right" onclick="next()">></div>





The error which I am getting at the moment is "TypeError: Cannot read property 'classList' of undefined".

Answer

Please try below.

var yogNumber = 0;
var yogs = document.querySelectorAll('.yog');

function next() {
  yogNumber++;
  if (yogs.length > yogNumber) {
    document.querySelector('.active').classList.remove('active');
    yogs[yogNumber].classList.add('active');
  }
  else{
    yogNumber=0;
    document.querySelector('.active').classList.remove('active');
    yogs[yogNumber].classList.add('active');
    }

}

function previous() {
  yogNumber--;
  if(yogNumber<0)
    {
      document.querySelector('.active').classList.remove('active');
    yogs[yogs.length-1].classList.add('active');
      yogNumber=yogs.length-1;
      }
  else if (yogs.length > yogNumber) {
    document.querySelector('.active').classList.remove('active');
    yogs[yogNumber].classList.add('active');
  }

}
.yog {
  display: none
}
.active {
  display: block
}
<div class="yog active">
  <div id="heading">Text 1</div>
</div>

<div class="yog">
  <div id="heading">Text 2</div>
</div>

<div class="yog">
  <div id="heading">Text 3</div>
</div>

<div class="yog">
  <div id="heading">Text 4</div>
</div>
<br />
<div id="left" onclick="previous()">
  <</div>
    <br />
    <div id="right" onclick="next()">></div>