1

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>
David
  • 208,112
  • 36
  • 198
  • 279
david
  • 13
  • 2
  • Try ++index, not index++ more info here: https://stackoverflow.com/questions/3469885/somevariable-vs-somevariable-in-javascript – Mateusz Jan 18 '23 at 14:30
  • If I were to *guess* based on the code shown... You may be looking for `--currentIndex` instead of `currentIndex--`, particularly if you're relying on the result of that expression to already be incremented/decremented. – David Jan 18 '23 at 14:30
  • 1
    @JarosławCh. Thank you that worked exactly how I wanted it to!! – david Jan 18 '23 at 14:35
  • @David Thank you as well. I will check out that guide. – david Jan 18 '23 at 14:36

1 Answers1

0

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.

Mateusz
  • 175
  • 9