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>