Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do my next and Prev buttons not follow the array index properly?

I am trying to create a gallery of maps in an iframe with next and prev buttons. However, currently instead of following the order of the array it doesn’t follow the order the elements of the array are in.

I want it so that the first link is displayed by default. Then when clicking next it should go to the next link/index and clicking prev goes to the previous link/index. Currently, it starts at [0] which is good, but then clicking next sends it to [0] again. Then on the third click to [1]. Even more strangely clicking the prev button sends it to [2] for some reason. it follows the pattern of [0, 1, 2, 1, 0, 1, 2, 1, 0], etc.

const prevButton = document.querySelector('.prev');
const nextButton = document.querySelector('.next');
const mapsList = [ 'link 1', 'link 2', 'link 3'];
const iframe = document.getElementById('mapsframe').src = mapsList[0];
let currentIndex = 0 ;

prevButton.addEventListener('click', function() {
  document.getElementById('mapsframe').setAttribute('src', mapsList[currentIndex--]);
  nextButton.disabled = false;
  if (currentIndex === 0) {
    prevButton.disabled=true ;
  }
});
    
nextButton.addEventListener('click', function() {
  document.getElementById('mapsframe').setAttribute('src', mapsList[currentIndex++]);
  prevButton.disabled = false; 
  if (mapsList.length === currentIndex + 1) {
    nextButton.disabled = true;
  }
});
<div class="maps-gallery">
  <iframe src="" id="mapsframe" name="mapsframe" width="750" height="400" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
</div>
</section>
<div class="buttons">
  <button disabled="" class="button prev">Prev</button>
  <button class="button next">Next</button>
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It can happen because you use:

document.getElementById('mapsframe').setAttribute('src', mapsList[currentIndex++]);

Try to use:

document.getElementById('mapsframe').setAttribute('src', mapsList[++currentIndex]);

There is a difference because the first way will change the iframe src and then increase your index while the second way will increase your index and then change src.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading