The function plusSlides is called in my html via onclick. This shows the similar function and html I am using. The class mySlides
, holds the text that will display for each n==x
in showSlides
. Unlike the slideshow example in the link, my function does not work when I try to click on onclick="plusSlides(-1)"
. For instance, when I click three times on plusSlides(-1)
, both aerialMap
and fedTiless
are added but roadMap
is not. Would anyone know why?
function roadMap() {
map.addLayer(Road);
map.removeLayer(febTiles);
}
function febTiless() {
map.addLayer(febTiles);
map.removeLayer(Road);
}
function aerialMap() {
map.addLayer(Aerial);
map.removeLayer(febTiles);
map.removeLayer(Road);
}
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var slides = document.getElementsByClassName("mySlides");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
if(n == 1)
aerialMap();
if(n == 2)
febTiless();
if(n == 3)
roadMap();
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slideIndex-1].style.display = "block";
}
The bug is in this part of the code:
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
if(n == 1)
aerialMap();
if(n == 2)
febTiless();
if(n == 3)
roadMap();
In the first two lines the slideIndex variable is adjusted (correctly) to cycle back into the valid range of slide numbers, but the if
conditions that follow are still based on n, which has not been adjusted in that way, so n will be 0 (or 4) in some cases, and then none of the if
conditions will be true
.
So adjust like this:
var slideIndex;
showSlides(1);
function plusSlides(n) {
showSlides(slideIndex + n); // avoid assignment here
}
function currentSlide(n) {
showSlides(n); // avoid assignment here
}
function showSlides(n) {
var slides = document.getElementsByClassName("mySlides");
slideIndex = n; // assign only here, at a single place
// Don't use n anymore, only work with slideIndex
if (slideIndex > slides.length) {slideIndex = 1}
if (slideIndex < 1) {slideIndex = slides.length}
if(slideIndex == 1)
aerialMap();
if(slideIndex == 2)
febTiless();
if(slideIndex == 3)
roadMap();
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slideIndex-1].style.display = "block";
}